Python3 元组
- Python 的元组与列表类似,不同之处在于元组的元素不能修改。
- 元组使用小括号,列表使用方括号。
创建元组
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
如下实例:
1 2 3 |
tup1 = ('hello', 'py40', 0, 10000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d"; |
创建空元组
1 |
tup1 = (); |
元组中只包含一个元素时,需要在元素后面添加逗号
1 |
tup1 = (50,); |
元组与字符串类似,下标索引从0开始,可以进行截取,组合等。
访问元组
元组可以使用下标索引来访问元组中的值,如下实例:
1 2 3 4 |
>>> tup1 = ('hello', 'py40', 0, 10000) >>> print(tup1[0]) hello >>> |
元组元素修改
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合。
1 2 3 |
##这样非法 tup1 = ('hello', 'py40', 0, 10000) tup1[0] = 1 |
我们要新增元组的元素,可以通过连接元组来实现。
新增元素实例:
1 2 3 4 5 6 |
>>> tup1 = ('hello', 'py40', 0, 10000) >>> tup2 = (1,) >>> tup3 = tup1+tup2 >>> print(tup3) ('hello', 'py40', 0, 10000, 1) >>> |
或者
1 2 3 4 5 6 |
#添加元组 >>> tup1 = ('hello', 'py40', 0, 10000) >>> tup1 = (tup1 ,'05') >>> print(tup1) (('hello', 'py40', 0, 10000), '05') >>> |
元组的元素是不能被删除的,但是可以删除整个元组
1 2 3 4 5 6 7 |
>>> tup2 = (1,) >>> del tup2 >>> print(tup2) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'tup2' is not defined >>> |
判断元素是否存在
1 2 3 |
>>> tup1 = ('hello', 'py40', 0, 10000) >>> print(1 in tup1) False |
元组遍历
元组的遍历需要使用for循环,关于for循环的使用,将在python循环章节讲解。
1 2 |
tup1 = ('hello', 'py40', 0, 10000) for x in tup1:print(x) |
元组内置函数
Python元组包含了以下内置函数
方法 | 描述 |
---|---|
len(tuple) | 计算元组元素个数。 |
max(tuple) | 返回元组中元素最大值。 |
min(tuple) | 返回元组中元素最小值。 |
tuple(seq) | 将列表转换为元组。 |
未经允许不得转载:Python在线学习 » 【第九节】Python元组