運算符
運算符 |
描述 |
支持的類型 |
+ |
合并 |
字符串、列表、元組 |
* |
復制 |
字符串、列表、元組 |
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'}