python 4
一、列表相关操作
l = ['布偶猫', '小断腿', '大白']
# 1. append
l.append('哎呀')
print(l)
# 2. insert
l.insert(0, '小猪佩琪')
print(l)
# 3. extend
l.extend('猪猪')
print(l)
# 4. pop 此动作有返回值
print(l.pop(-1))
print(l)
# 5. remove
l.remove('猪')
print(l)
# 6. clear
l.clear()
print(l)
# 7. del
l = ['小猪佩琪', '布偶猫', '小断腿', '大白', '哎呀']
del l # 在内存级别直接删除列表 print(l) 会报错
l = ['小猪佩琪', '布偶猫', '小断腿', '大白', '哎呀']
del l[3] # 按照索引删除
print(l)
del l[1::2] # 按照切片+步长删除
print(l)
# 8. 索引=x
l[1] = '小老婆'
print(l)
# 9. 切片=xxxxxxxx
l = ['小猪佩琪', '布偶猫', '小断腿', '大白', '哎呀']
l[1:] = '一头猪', '两头猪', '3', '5', '7'
print(l)
# 10. sort
l.sort()
print(l)
l.sort(reverse = True)
print(l)
# 11. reverse
l.reverse()
print(l)
['布偶猫', '小断腿', '大白', '哎呀']
['小猪佩琪', '布偶猫', '小断腿', '大白', '哎呀']
['小猪佩琪', '布偶猫', '小断腿', '大白', '哎呀', '猪', '猪']
猪
['小猪佩琪', '布偶猫', '小断腿', '大白', '哎呀', '猪']
['小猪佩琪', '布偶猫', '小断腿', '大白', '哎呀']
[]
['小猪佩琪', '布偶猫', '小断腿', '哎呀']
['小猪佩琪', '小断腿']
['小猪佩琪', '小老婆']
['小猪佩琪', '一头猪', '两头猪', '3', '5', '7']
['3', '5', '7', '一头猪', '两头猪', '小猪佩琪']
['小猪佩琪', '两头猪', '一头猪', '7', '5', '3']
['3', '5', '7', '一头猪', '两头猪', '小猪佩琪']
Process finished with exit code 0
二、嵌套
l = ['qiqi', 'aiya', [99, ' xiaolaji', '98'], 21]
l[0] = l[0].upper()
print(l)
l[2][1] = l[2][1].strip().capitalize()
print(l)
l[2][0] = str(l[2][0] + 1)
print(l)
l[2][2] = int(l[2][2]) + 2
print(l)
['QIQI', 'aiya', [99, ' xiaolaji', '98'], 21]
['QIQI', 'aiya', [99, 'Xiaolaji', '98'], 21]
['QIQI', 'aiya', ['100', 'Xiaolaji', '98'], 21]
['QIQI', 'aiya', ['100', 'Xiaolaji', 100], 21]
Process finished with exit code 0
三、元组
# 元组 只读列表,不能增删改 只能查询
tu = (11, 22, 33, 44, 55)
# 索引,切片,步长
print(tu[0])
print(tu[:3:2])
for i in tu:
print(i)
# 元组内的列表可以修改
tu1 = ('wusir', 'alex', [22, 44, 'taibai'],)
tu1[-1].append('女神')
print(tu1)
del tu1 # 从内存删除元组 print(tu1) 找不到元组,会报错# 元组 只读列表,不能增删改 只能查询
tu = (11, 22, 33, 44, 55)
# 索引,切片,步长
print(tu[0])
print(tu[:3:2])
for i in tu:
print(i)
# 元组内的列表可以修改
tu1 = ('wusir', 'alex', [22, 44, 'taibai'],)
tu1[-1].append('女神')
print(tu1)
del tu1 # 从内存删除元组 print(tu1) 找不到元组,会报错
四、range
>>> for i in range(0, 101, 2):
... print(i)
...
0
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100