目录
一、运算符
运算符 | 描述 | 支持的类型 |
+ | 合并 | 字符串、列表、元组 |
* | 复制 | 字符串、列表、元组 |
in | 元素是否存在 | 字符串、列表、元组、字典 |
not in | 元素是否不存在 | 字符串、列表、元组、字典 |
1. 合并(+)
str1 = 'a'
str2 = 'b'
list1 = [1, 2]
list2 = [10, 11]
tuple1 = (1, 2)
tuple2 = (10, 11)
dict1 = {'name': 'Tom'}
dict2 = {'age': 20}
# + 合并
print(str1 + str2) # ab
print(list1 + list2) # [1, 2, 10, 11]
print(tuple1 + tuple2) # [1, 2, 10, 11]
print(dict1 + dict2) # 报错 → 不支持
2.复制(*)
str = 'a'
list = [1, 2]
tuple = (1, 2)
dict = {'name': 'Tom'}
# * 复制
print(str1 * 2) # aa
print(list1 * 3) # [1, 2, 1, 2, 1, 2]
print(tuple1 * 4) # (1, 2, 1, 2, 1, 2, 1, 2)
print(dict1 * 5) # 报错
3.in / not in
str0 = 'abcd'
list0 = [1, 2, 3, 4]
tuple0 = (1, 2, 3, 4)
dict0 = {'name': 'Tom', 'age': 20}
# in / not in
print('a' in str0) # T
print('a' not in str0) # F
print(2 in list0) # T
print(2 not in list0) # F
print(5 in tuple0) # F
print(5 not in tuple0) # T
print('gender' in dict0) # F
print('gender' not in dict0) # T
print('name' in dict0.keys()) # T
print('Tom' in dict0.values()) # T
二、通用函数
函数名 | 描述 |
len() | 元素个数 |
del或del() | 删除(全部或指定下标处) |
max() | 返回元素最大值 |
min() | 返回元素最小值 |
range(start, end, step) | 生成从start到end的数字,步长为step,供for循环使用 |
enumerate() | 将一个可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标,一般用在for循环中 |
1.len()
str0 = 'abcd'
list0 = [1, 2, 3, 4]
tuple0 = (1, 2, 3, 4, 5)
dict0 = {'name': 'Tom', 'age': 20, 'gender': 'man'}
print(len(str0)) # 4
print(len(list0)) # 4
print(len(tuple0)) # 5
print(len(dict0)) # 3
2.del / del()
字符串、元组只能删除整体,不能删除其中一位
mystr = 'abcd'
mylist = [1, 2, 3, 4]
mytuple = (1, 2, 3, 4, 5)
mydict = {'name': 'Tom', 'age': 20, 'gender': 'man'}
del mystr
print(mystr) # NameError: name 'mystr' is not defined
del mylist[0]
print(mylist) # [2, 3, 4]
del(mylist)
print(mylist) # NameError: name 'mystr' is not defined
del mytuple
print(mytuple) # NameError: name 'mystr' is not defined
del mydict['name']
print(mydict)
del(mydict) # {'age': 20, 'gender': 'man'}
print(mydict) # NameError: name 'mydict' is not defined
3.max / min
str0 = 'abcd'
list0 = [1, 2, 3, 4]
tuple0 = (0, 1, 2, 3, 4, 5)
dict0 = {'name': 'Tom', 'age': 20, 'gender': 'man'}
print(max(str0)) # d
print(min(str0)) # a
print(max(list0)) # 4
print(min(list0)) # 1
print(max(tuple0)) # 5
print(min(tuple0)) # 0
print(max(dict0)) # name
print(min(dict0)) # age
4.range(start, end, step)
生成从start到end的数字,步长为step,供for循环使用
输出不包含end位
start默认为0,step默认为1
#1 2 3 4 5 6 7 8 9
for i in range(1, 10, 1):
print(i, end=' ')
print('\n')
#1 3 5 7 9
for i in range(1, 10, 2):
print(i, end=' ')
print('\n')
#0 1 2 3 4 5 6 7 8 9
for i in range(10):
print(i, end=' ')
print('\n')
5.enumerate()
已知一个序列,从起始值开始输出数字和对应数据,一般用在for循环中
语法
enumerate(可遍历对象, start = 0)
start为遍历数据的下标的起始值,默认为0
new_list = ['a', 'b', 'c', 'd', 'e', 'f']
'''
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
'''
for i in enumerate(new_list):
print(i)
'''
(4, 'a')
(5, 'b')
(6, 'c')
(7, 'd')
(8, 'e')
(9, 'f')
'''
for i in enumerate(new_list, start = 4):
print(i)