Python3元组
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
访问元组
访问元组和访问列表基本一样,不再赘述!
修改元组
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合以及删除。
连接
>>> a = (1,2,3) >>> b = ('a','b','c') >>> c = a+b >>> c (1, 2, 3, 'a', 'b', 'c')
删除
>>> a = (1,2,3) >>> del(a) >>> a Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> a NameError: name 'a' is not defined
元组运算符
与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。
| Python 表达式 | 结果 | 描述 |
|---|---|---|
| len((1, 2, 3)) | 3 | 计算元素个数 |
| (1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 连接 |
| ('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | 复制 |
| 3 in (1, 2, 3) | True | 元素是否存在 |
| for x in (1, 2, 3): print (x,) | 1 2 3 | 迭代 |
元组的内置函数
Python元组包含了以下内置函数
| 序号 | 方法及描述 | 实例 |
|---|---|---|
| 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')
|
浙公网安备 33010602011771号