赞
踩
列表是用方括号标注,逗号分隔的一组值。列表是有序集合,没有固定大小,可以包含不同类型的元素,但一般情况下,各个元素的类型相同。
语法:[element1,element2,
⋯
\cdots
⋯]
1.1创建一个普通列表
x=["apple","orange","grape","banana","cherry"]
y=[23,45,-12,345,-78]
z=list(range(1,10,3)) # 利用range()函数,1-10,3为间隔,左闭右开
print(x,type(x))
print(y,type(y))
print(z,type(z))
[‘apple’, ‘orange’, ‘grape’, ‘banana’, ‘cherry’] <class ‘list’>
[23, 45, -12, 345, -78] <class ‘list’>
[1, 4, 7]
1.2 利用推导式创建列表(List comprehensions)
x=[i for i in range(10,1,-2)]
print(x)
y=[j for j in range(50) if (j % 2) != 0 and (j % 3) == 0]
print(y)
z=[(x, y) for x in [1,2,3] for y in [3,1] if x != y]
print(z,type(z))
[10, 8, 6, 4, 2]
[3, 9, 15, 21, 27, 33, 39, 45]
[(1, 3), (2, 3), (2, 1), (3, 1)] <class ‘list’>
list.append(obj):在列表末尾添加新的对象
list.extend(seq) :通过添加可迭代对象中的所有项来扩展列表
list.insert(index, obj): 在编号 index 位置插入 obj
fruit=["apple","orange","grape"]
x=fruit.append(["banana","cherry"]) # 追加,把一个东西整体添加在列表后
print(x,type(x),len(x))
y=fruit.extend(["banana","cherry"]) # 扩展,把一个东西里的所有元素添加在列表后。
print(y,type(y),len(y))
z=fruit.insert(2,"cherry")
print(z)
[‘apple’, ‘orange’, ‘grape’, [‘banana’, ‘cherry’]] <class ‘list’> 4
[‘apple’, ‘orange’, ‘grape’, ‘banana’, ‘cherry’] <class ‘list’> 5
[‘apple’, ‘orange’, ‘cherry’, ‘grape’]
list.remove(obj): 移除列表中某个值的第一个匹配项
del var1[, var2 ……] 删除单个或多个对象。
x=["apple","orange","grape","banana","cherry"]
x.remove("orange")
print(x)
[‘apple’, ‘grape’, ‘banana’, ‘cherry’]
x=["apple","orange","grape","banana","cherry"]
del x[0:2]
print(x)
[‘banana’, ‘cherry’]
5.1 通过索引获取:
列表从左到右第一个元素索引是0,如果是从右到左最后一个元素索引是-1
x=["apple","orange","grape","banana",["cherry","pear"]]
print(x[0],type(x[0]))
print(x[-1],type(x[-1]))
apple <class ‘str’>
[‘cherry’, ‘pear’] <class ‘list’>
5.2 通过切片:
切片是列表和字符串最常用的获取元素的方法,语法是:
start : stop : step
其中又可以分以下几种情况
切片 | 含义 |
---|---|
start : | 以 step 为 1 (默认) 从编号 start 往列表尾部切片。 |
: stop | 以 step 为 1 (默认) 从列表头部往编号 stop 切片 |
start : stop | 以 step 为 1 (默认) 从编号 start 往编号 stop 切片 |
start : stop : step | 以具体的 step 从编号 start 往编号 stop 切片 |
: | 复制列表中的所有元素(浅拷贝) |
x=["apple","orange","grape","banana","cherry","pear"]
print(x[2:]) # ['grape', 'banana', 'cherry', 'pear']
print(x[-2:]) # ['cherry', 'pear']
print(x[:-3]) # ['apple', 'orange', 'grape']
print(x[:2]) # ['apple', 'orange']
print(x[0:4:2]) # ['apple', 'grape']
print(x[::-1]) # ['pear', 'cherry', 'banana', 'grape', 'orange', 'apple']
print(x[:3:2]) # ['apple', 'grape']
print(x[1::2]) # ['orange', 'banana', 'pear']
等号:==
连接:+
重复:*
成员关系:in , not in
list1 = [123, 456]
list2 = [456, 123]
list3 = [123, 456]
print(list1 == list2) # False
print(list1 == list3) # True
list4 = list1 + list2 # extend()
print(list4) # [123, 456, 456, 123]
list3 *= 3
print(list3) # [123, 456, 123, 456, 123, 456]
print(123 in list3) # True
print(456 not in list3) # False
引号之间的字符集合,支持成对的单引号或双引号
t1='5'+'8'
t2="i love China"
print(t1) # 58
print(t2) # i love China
与列表相似,这里举个例子示意:
s=“Chinese”
操作 | 结果 |
---|---|
s[0:2] | Ch |
s[1::3] | he |
s[:-4:2] | Ci |
s[::-1] | esenihC |
方法 | 含义 |
---|---|
split(str="", num) | 以 str 为分隔符截取字符串(默认空格),如果 num 有指定值,则仅截取 num+1 个子字符串(默认为-1即所有) |
join(seq) | 序列中的元素以指定的字符连接生成一个新的字符串 |
capitalize() | 将字符串的第一个字符转换为大写 |
lower() / upper() | 转换字符串中所有大写(小写)字符为小写(大写) |
count(str) | 返回str在 string 里面出现的次数 |
url = "http://www.baidu.com/python/image/123456.jpg"
path1 =url.split(".") # 以“.” 进行分隔
path2 =url.split("/")[-1] # 分割之后是 ['http:', '', 'www.baidu.com', 'python', 'image', '123456.jpg'],再索引
print(path1)
print(path2)
[‘http://www’, ‘baidu’, ‘com/python/image/123456’, ‘jpg’]
123456.jpg
与列表类似,但是元组不可修改
语法:(element1,element2,
⋯
\cdots
⋯)
t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python' # 不需要括号也可以
print(t1, type(t1))
print(t2, type(t2))
x = (1)
print(type(x)) # <class 'int'>
x = (1,) # 单个元素的元组需要加逗号
print(type(x)) # <class 'tuple'>
x = ()
print(type(x)) # <class 'tuple'>
(1, 10.31, ‘python’) <class ‘tuple’>
(1, 10.31, ‘python’) <class ‘tuple’>
<class ‘int’>
<class ‘tuple’>
<class ‘tuple’>
week = ('Monday', 'Tuesday', 'Thursday', 'Friday')
week = week[:2] + ('Wednesday',) + week[2:]
print(week)
(‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’)
元组中的元素值是不允许删除的,但可以使用del语句来删除整个元组
等号操作符:==
连接操作符 +
重复操作符 *
成员关系操作符 in、not in
字典是无序的 键:值(key:value)对集合,在同一个字典中键必须是互不相同的
值,可以取任何数据类型,但键必须是不可变的,如字符串,数字等。
语法:{key1:value1,key2:value2,
⋯
\cdots
⋯}
大括号 – 把所有元素绑在一起
逗号 – 将每个键值对分开
冒号 – 将键和值分开
1.1 直接创建:{ }
capital={'China':'Beijing','America':'NewYork','Japan':'Tokyo'}
print(capital,type(capital),capital['Japan'])
dt={'abc':123,98.6:23}
print(dt[98.6])
{‘China’: ‘Beijing’, ‘America’: ‘NewYork’, ‘Japan’: ‘Tokyo’} <class ‘dict’> Tokyo
23
1.2 dict()函数
dt1=dict()
dt1['a']=1
dt1['b']=2
dt2=dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
print(dt1,"\n",dt2)
{‘a’: 1, ‘b’: 2}
{‘sape’: 4139, ‘guido’: 4127, ‘jack’: 4098}
函数/方法 | 描述 |
---|---|
len(dict) | 返回字典的元素个数(键的个数) |
dict.clear() | 删除字典内的所有元素 |
dict.get(key, default=None) | 返回指定键的值,如果值不在字典中返回默认值 |
集合与字典类似,是一组key的集合,但不存储value,且集合中key不重复(与数学上集合概念相似)
A set is an unordered collection with no duplicate elements
由于set存储的是无序集合,所以不能索引或切片
week={'Monday','Tuesday','Wednesday','Thrusday'}
print(week,type(week),len(week))
num=set('12345')
print(num,type(num),len(num))
{‘Wednesday’, ‘Thrusday’, ‘Tuesday’, ‘Monday’} <class ‘set’> 4
{‘1’, ‘4’, ‘2’, ‘5’, ‘3’} <class ‘set’> 5
方法 | 描述 | 用法 |
---|---|---|
intersection() / & | 返回两个集合的交集 | c=a.intersection(b) / c=a&b |
union() / | | 返回两个集合的并集 | c=a.intersection(b) / c=a | b |
difference() / – | 返回两个集合的差集 | c=a.difference(b) / c=a-b |
len() | 返回集合的大小 | len(a) |
参考连接:
https://www.runoob.com/python3/python3-tutorial.html
https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
https://tianchi.aliyun.com/notebook-ai/detail?spm=5176.19700039.J_9059755190.4.68f13ff4I0F6Vx&postId=169962
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。