1.列表和元组的区别
1.一个元组由数个逗号分隔的值组成
2.元组是不可变的,列表是可变的
3.创建列表用[] 创建元组用()
2.元组的创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| >>> tuple1 = (1,2,3,4,5) >>> type(tuple1) <class 'tuple'> >>> tuple2 = (1,) >>> type(tuple2) <class 'tuple'> >>> tuple3 = 1,2,3,4,5 >>> type(tuple3) <class 'tuple'> >>> tuple4 = () >>> type(tuple4) <class 'tuple'> >>> tuple5 = (1,2,3,4,'python',True) >>> type(tuple5) <class 'tuple'>
|
以下不是元组
1 2 3
| >>> tuple1 = (1) >>> type(tuple1) <class 'int'>
|
3.元组取值
1 2 3 4 5
| >>> temp = ('android', True, ['python', 'kotlin']) >>> temp[0] 'android' >>> temp[2] ['python', 'kotlin']
|
4.元组的更新
1 2 3 4
| >>> temp = ('android','java','kotlin') >>> temp = temp[:1] + ('python',) + temp[1:] >>> temp ('android', 'python', 'java', 'kotlin')
|
1 2 3 4 5 6 7
| >>> temp = ('android',True,[1,'zxy']) >>> temp ('android', True, [1, 'zxy']) >>> temp[2][0] = 'python' >>> temp[2][1] = 'kotlin' >>> temp ('android', True, ['python', 'kotlin'])
|
tuple所谓的“不可变”是说,tuple的每个元素,指向永远不变。即指向’android’,就不能改成指向True,
指向的这个列表[1,’zxy’]本身是可变的!
5.元组的删除,删除整个元组
6.元组的操作符
*
1 2 3
| >>> temp = (1,2,3,4) >>> temp * 2 (1, 2, 3, 4, 1, 2, 3, 4)
|
>、<
1 2 3 4
| >>> temp = (1,2,3,4) >>> temp1 = (2,3,4,5) >>> temp < temp1 True
|
in
1 2 3
| >>> temp = (1,2,3,4) >>> 1 in temp True
|