Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号 ( ),列表使用方括号 [ ]。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
>>> tup1 = ('Google', 'W', 1997, 2000)
>>> tup2 = (1, 2, 3, 4, 5 )
>>> tup3 = "a", "b", "c", "d" # 不需要括号也可以
>>> type(tup3)
<class 'tuple'></class>
创建空元组
tup1 = ()
元组中只包含一个元素时,需要在元素后面添加逗号 , ,否则括号会被当作运算符使用:
>>> tup1 = (50)
>>> type(tup1) # 不加逗号,类型为整型
<class 'int'>
>>> tup1 = (50,)
>>> type(tup1) # 加上逗号,类型为元组
<class 'tuple'></class></class>
元组与字符串类似,下标索引从 0 开始,可以进行截取,组合等。
正索引0 1 2 3 值 GoogleW1997 2020 负索引-4 -3 -2 -1
元组可以使用下标索引来访问元组中的值,如下实例:
#!/usr/bin/python3
tup1 = ('Google', 'W', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
以上实例输出结果:
tup1[0]: Google
tup2[1:5]: (2, 3, 4, 5)
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:
#!/usr/bin/python3
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
以下修改元组元素操作是非法的。
tup1[0] = 100
创建一个新的元组
tup3 = tup1 + tup2
print (tup3)
#结果
(12, 34.56, 'abc', 'xyz')
元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:
#!/usr/bin/python3
tup = ('Google', 'Runoob', 1997, 2000)
print (tup)
del tup
print ("删除后的元组 tup : ")
print (tup)
以上实例元组被删除后,输出变量会有异常信息,输出如下所示:
删除后的元组 tup :
Traceback (most recent call last):
File "test.py", line 8, in <module>
print (tup)
NameError: name 'tup' is not defined</module>
与字符串一样,元组之间可以使用 +、+=和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。
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迭代
因为元组也是一个序列,所以我们可以访问元组中的指定位置的元素,也可以截取索引中的一段元素,如下所示:
元组:
L = ('Google', 'Taobao', 'W')
Python 表达式结果描述L[2]’W’读取第三个元素L[-2]’Taobao’反向读取;读取倒数第二个元素L1:截取元素,从第二个开始后的所有元素。
运行实例如下:
>>> L = ('Google', 'Taobao', 'W')
>>> L[2]
'W'
>>> L[-2]
'Taobao'
>>> L[1:]
('Taobao', 'W')
Python元组包含了以下内置函数
序号方法及描述实例1len(tuple)
计算元组元素个数。>>> tuple1 = (‘Google’, ‘W’, ‘Taobao’)
len(tuple1)
2max(tuple)
返回元组中元素最大值。>>> tuple2 = (‘5’, ‘4’, ‘8’)
max(tuple2)
‘8’
3min(tuple)
返回元组中元素最小值。>>> tuple2 = (‘5’, ‘4’, ‘8’)
min(tuple2)
‘4’
4tuple(seq)
将列表转换为元组。>>> list1= [‘Google’, ‘Taobao’, ‘Q’, ‘Baidu’]
tuple1=tuple(list1)
tuple1
(‘Google’, ‘Taobao’, ‘Q’, ‘Baidu’)5operator(tuple1,tuple2)
较两个元组元素>>> import operator
dict1 = (1, 2, 3)
dict2 = (‘a’, ‘b’, ‘c’)
operator.eq(dict1, dict2)
False
所谓元组的不可变指的是元组所指向的内存中的内容不可变。
>>> tup = ('W', '3', 'C', 's', 'c', 'h','o','o','l')
>>> tup[0] = 'w' # 不支持修改元素
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> id(tup) # 查看内存地址
4440687904
>>> tup = (1,2,3)
>>> id(tup)
4441088800 # 内存地址不一样了</module></stdin>
从以上实例可以看出,重新赋值的元组 tup,绑定到新的对象了,不是修改了原来的对象。
Original: https://blog.csdn.net/weishuai90/article/details/128750544
Author: ws的大数据田地
Title: Python3 元组
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/814256/
转载文章受原作者版权保护。转载请注明原作者出处!