Python的元组与列表类似,不同之处在于元组的元素不能修改或删除。
创建元组
>>> tup1 = () #创建空元组
>>> tup2 = (1)
>>> type(tup2)
<class 'int'>
>>> tup3 = (1,) #创建只有一个元素的元组
>>> type(tup3)
<class 'tuple'>
不支持增加、修改、删除元组
>>> tup3[1] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> tup3[0] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> del tup3[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
切片:取多个元素
>>> tup1 = ('Amy','Bob','Cindy','David','Eric')
>>> tup1[1:4]
('Bob', 'Cindy', 'David')
>>> tup1[:4]
('Amy', 'Bob', 'Cindy', 'David')
>>> tup1[1:]
('Bob', 'Cindy', 'David', 'Eric')
>>> tup1[::2]
('Amy', 'Cindy', 'Eric')
>>> tup1[-2]
'David'
统计
>>> tup1
('Amy', 'Bob', 'Cindy', 'David', 'Eric')
>>> tup1 = ('Amy','Bob','Amy','Bob')
>>> tup1.count('Amy')
2
>>> tup1.count('Bob')
2
索引
>>> tup1
('Amy', 'Bob', 'Amy', 'Bob')
>>> tup1.index('Amy')
0 #只返回找个的第一个索引
>>> tup1.index('Bob')
1
>>> tup1.index('Cindy')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
与tuple相关的函数
序号 | 方法及描述 | 实例 |
---|---|---|
1 | len(tuple) 计算元组元素个数。 | >>> tuple1 = ('Google', 'Runoob', 'Taobao') >>> len(tuple1) 3 >>> |
2 | max(tuple) 返回元组中元素最大值。 | >>> tuple2 = ('5', '4', '8') >>> max(tuple2) '8' >>> |
3 | min(tuple) 返回元组中元素最小值。 | >>> tuple2 = ('5', '4', '8') >>> min(tuple2) '4' >>> |
4 | tuple(seq) 将列表转换为元组。 | >>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1=tuple(list1) >>> tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu') |
tuple的内置方法
序号 | 方法 |
---|---|
1 | tuple.index(obj) 从元组中找出某个值第一个匹配项的索引位置 |
2 | tuple.count(obj) 统计某个元素在元组中出现的次数 |
参考链接:http://www.runoob.com/python3/python3-tuple.html