list和tuple是Python内置的有序集合,一个可变,一个不可变。根据需要来选择使用它们。
1.内置数据类型,列表List
>>> appleVersion = [‘apple1‘,‘apple2‘,‘apple3‘] >>> appleVersion [‘apple1‘, ‘apple2‘, ‘apple3‘] >>> len(appleVersion) 3 >>> appleVersion[0] ‘apple1‘ >>> appleVersion[1] ‘apple2‘ >>> appleVersion[2] ‘apple3‘ >>> appleVersion[3] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of rang
倒序打印
>>> appleVersion[-1] ‘apple3‘ >>> appleVersion[-2] ‘apple2‘ >>> appleVersion[-3] ‘apple1‘ >>> appleVersion[-4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
新增
>>> appleVersion.append(‘orange‘) >>> appleVersion [‘apple1‘, ‘apple2‘, ‘apple3‘, ‘orange‘]
插入
>>> appleVersion.insert(1,‘banana‘) >>> appleVersion [‘apple1‘, ‘banana‘, ‘apple2‘, ‘apple3‘, ‘orange‘]
删除末尾/删除索引i
>>> appleVersion.pop() ‘orange‘ >>> appleVersion [‘apple1‘, ‘banana‘, ‘apple2‘, ‘apple3‘] >>> appleVersion.pop(1) ‘banana‘ >>> appleVersion [‘apple1‘, ‘apple2‘, ‘apple3‘]
赋值替换
>>> appleVersion[1]=‘orange‘ >>> appleVersion [‘apple1‘, ‘orange‘, ‘apple3‘]
List嵌套
>>> orange=[‘orange1‘,‘orange2‘] >>> apple=[‘apple1‘,123,orange,True] >>> apple [‘apple1‘, 123, [‘orange1‘, ‘orange2‘], True] >>> len(apple) 4
2. tuple和list非常类似,但是tuple一旦初始化就不能修改,不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。
tuple的陷阱:
当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来
>>> lemon=(‘lemon1‘,‘lemon2‘,‘lemon3‘) >>> lemon (‘lemon1‘, ‘lemon2‘, ‘lemon3‘) >>> lemon1=() >>> lemon1 () 数字1 >>> lemon2=(1) >>> lemon2 1 一个原素 >>> lemon3=(1,) >>> lemon3 (1,) >>> lemon4=(‘a‘,‘b‘,[‘A‘,‘B‘]) >>> lemon4[2][0]=‘X‘ >>> lemon4[2][1]=‘Y‘ >>> lemon4 (‘a‘, ‘b‘, [‘X‘, ‘Y‘])
表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。
tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向‘a‘,就不能改成指向‘b‘,指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的!
理解了“指向不变”后,要创建一个内容也不变的tuple,那就必须保证tuple的每一个元素本身也不能变
时间: 2024-10-14 05:47:59