Python中的元组(tuple)是一种不可变的序列类型,它支持多种操作。以下是一些常用的元组操作:
t = (1, 2, 3)
tuple()函数:t = tuple([1, 2, 3])
print(t[0]) # 输出: 1
print(t[1:3]) # 输出: (2, 3)
len()函数获取元组的长度:print(len(t)) # 输出: 3
+操作符连接两个元组:t1 = (1, 2)
t2 = (3, 4)
print(t1 + t2) # 输出: (1, 2, 3, 4)
*操作符重复元组:print(t * 2) # 输出: (1, 2, 3, 1, 2, 3)
in或not in检查元素是否在元组中:print(2 in t) # 输出: True
print(4 not in t) # 输出: True
for循环遍历元组中的每个元素:for item in t:
print(item)
a, b, c = t
print(a) # 输出: 1
print(b) # 输出: 2
print(c) # 输出: 3
TypeError:t[0] = 4 # TypeError: 'tuple' object does not support item assignment
list()函数将元组转换为列表:t = (1, 2, 3)
lst = list(t)
print(lst) # 输出: [1, 2, 3]
tuple()函数将列表转换为元组:lst = [1, 2, 3]
t = tuple(lst)
print(t) # 输出: (1, 2, 3)
t = (x for x in range(5))
print(tuple(t)) # 输出: (0, 1, 2, 3, 4)
这些是Python中元组的一些基本操作。元组的不可变性使其在某些情况下比列表更安全和高效,特别是在需要确保数据不被意外修改的场景中。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。