Python-元组(tuple)

元组是不可变的
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。  

创建空元组:

tup1 = ()

元组函数:

(1,2,3)+(4,5,6)        # 连接两个元组
(("a",)*count)        # count为数量,复制字符串'a'乘'count'遍到元组
i in (1,2,3,i)        # 判断字符是否在元组内
for x in tuple        # 迭代元组

内置函数:

len((tuple))        # 计算元组长度
max(tuple)            # 返回元组中元素最大值
min(tuple)            # 返回元组中最小值
tuple(iterable)        # 将可迭代系列转换为元组    

注意:
如果元组中只有一个元素是,需要在元素后面添加逗号,否则括号会被当作运算符使用(变为整数型)

访问元组:

tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print(tup1)        # ('Google', 'Runoob', 1997, 2000)
print(tup2[1:5])        # (2, 3, 4, 5)

修改元组:

tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
tup3 = tup1 + tup2
print(tup3)    # ('Google', 'Runoob', 1997, 2000, 1, 2, 3, 4, 5, 6, 7)

删除元组:

tup1 = ('Google', 'Runoob', 1997, 2000)
print(tup1)     # ('Google', 'Runoob', 1997, 2000)
del tup1
print(tup1)    # NameError: name 'tup1' is not defined(无值)
原文地址:https://www.cnblogs.com/mamouren/p/13306854.html