运算符
运算符 |
描述 |
支持的类型 |
+ |
合并 |
字符串、列表、元组 |
* |
复制 |
字符串、列表、元组 |
in |
元素是否存在 |
字符串、列表、元组、字典 |
not in |
元素是否不存在 |
字符串、列表、元组、字典 |
str1 = 'aa'str2 = 'bb'list1 = [1, 2]list2 = [11, 22]t1 = (1, 2)t2 = (11, 22)dict1 = {'name', 'Python/ target=_blank class=infotextkey>Python'}dict2 = {'age': 30}# + 合并print(str1 + str2) # aabbprint(list1 + list2) # [1, 2, 11, 22]print(t1 + t2) # (1, 2, 11, 22)print(dict1 + dict2) # 字典不支持
str1 = 'a'list1 = ['hello']t1 = ('world',)# *:复制print(str1 * 5) # aaaaa# 打印10个-print('-' * 10) # ----------print(list1 * 5) # ['hello', 'hello', 'hello', 'hello', 'hello']print(t1 * 5) # ('world', 'world', 'world', 'world', 'world')
函数 |
描述 |
len() |
计算容器中元素个数 |
del或del() |
删除 |
max() |
返回容器中元素最大值 |
min() |
返回容器中元素最小值 |
range(start, end, step) |
生成从start到end的数字,步长为step,供for循环使用 |
enumerate() |
函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环中 |
len
str1 = 'asfasdfsd'list1 = [22, 3, 32, 31, 223]t1 = (12, 1, 2)s1 = {1, 2, 9, 4, 5, 6}dict1 = {'name': 'zs', 'age': 11}print(len(str1)) # 9print(len(list1)) # 5print(len(t1)) # 3print(len(s1)) # 6print(len(dict1)) # 2
del 或 del()
str1 = 'asfasdfsd'list1 = [22, 3, 32, 31, 223]t1 = (12, 1, 2)s1 = {1, 2, 9, 4, 5, 6}dict1 = {'name': 'zs', 'age': 11}# del str1# print(str1) # NameError: name 'str1' is not defined# del(list1[1])# print(list1) # [22, 32, 31, 223]# del(list1)# print(list1) # NameError: name 'list1' is not defined# del s1# print(s1) # NameError: name 's1' is not defined# del(dict1['age'])# print(dict1) # {'name': 'zs'}## del dict1# print(dict1) # NameError: name 'dict1' is not defined
max() 与 min()
str1 = 'asfasdfsd'list1 = [22, 3, 32, 31, 223]print(max(str1)) # sprint(min(str1)) # aprint(max(list1)) # 223print(min(list1)) # 3
range()
for i in range(1, 10, 1): print(i) # 1 2 3 4 5 6 7 8 9for i in range(1, 10, 2): print(i) # 1 3 5 7 9for i in range(10): print(i) # 0 1 2 3 4 5 6 7 8 9
enumerate()
enumerate(可遍历对象, start=0)
start参数用来设置遍历数据的下标的起始值,默认为0
list1 = ['a', 'b', 'c', 'd']# enumerate() 返回的结果是元组,元组第一个数据是原迭代对象的数据对应的下标,# 元组第二个数据是原迭代对象的数据for i in enumerate(list1): print(i)# (0, 'a')# (1, 'b')# (2, 'c')# (3, 'd')for i in enumerate(list1, start=1): print(i)# (1, 'a')# (2, 'b')# (3, 'c')# (4, 'd')
容器(数据)类型转换
- tuple():将某个序列转为元祖
- list():将某个序列转为列表
- set():将某个序列转为集合
list1 = [1, 2, 3, 4, 5]s1 = {11, 22, 33, 44, 55}t1 = ('a', 'b', 'c', 'd', 'e')# tuple():转为元组print(tuple(list1)) # (1, 2, 3, 4, 5)print(tuple(s1)) # (33, 11, 44, 22, 55)# list():转为列表print(list(s1)) # [33, 11, 44, 22, 55]print(list(t1)) # ['a', 'b', 'c', 'd', 'e']# set():转为集合print(set(list1)) # {1, 2, 3, 4, 5}print(set(t1)) # {'c', 'd', 'a', 'e', 'b'}