一、元组的概念
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用:
二、元组的运算
a = (23,45,67,899)
>>> type (a)
<class 'tuple'>
>>> a [-1]#选取元组中倒数第一的元素
899
>>> b = ('lazy','greedy','shy','kind')
>>> c = a + b#元组相加元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
>>> c
(23, 45, 67, 899, 'lazy', 'greedy', 'shy', 'kind')
>>> del a
SyntaxError: unexpected indent
>>> del(a)#删除元祖
>>> a
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
a
NameError: name 'a' is not defined
>>> c = ( 1,2,3,4,5,6,7)#
>>> len(c)#元组的运算
7
>>> max(c)
7
>>> min(c)
1
>>> 8 in (c)#判定
SyntaxError: unexpected indent
>>> 8 in c
false
三、常用函数
序号 | 方法及描述 | 实例 |
---|---|---|
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') |