元祖(tuple)是一种有序但不可变的集合,通常用圆括号编写,可以存放不同类型的数据。可以使用多种方式构建元祖:
使用一对圆括号来表示空元组: ()
使用一个后缀的逗号来表示单元组: a, 或 (a,)
使用以逗号分隔的多个项: a, b, c 或 (a, b, c)
使用内置的 tuple(): tuple() 或 tuple(iterable)
tuple()构造器用于构造一个元组,其中的项与 iterable 中的项具有相同的值与顺序。 iterable 可以是序列、支持迭代的容器或其他可迭代对象。 如果 iterable 已经是一个元组,会直接将其返回。 例如,tuple('abc') 返回 ('a', 'b', 'c') 。而 tuple( [1, 2, 3] ) 返回 (1, 2, 3)。 如果没有给出参数,构造器将创建一个空元组 ()。
决定生成元组的其实是逗号而不是圆括号。 圆括号只是可选的,生成空元组或需要避免语法歧义的情况除外。创建单个元祖时,(a)和a都属于单个变量,正确的方式是(a,)或者a,。
元祖支持正数索引和负数索引访问内部元素,第一个元素索引从0开始,最后一个元素负数索引为-1。
thistuple = ("apple", "banana", "cherry")
print(thistuple[0])
print(thistuple[-1])
元祖支持正数切片和负数切片,返回值是元祖。
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
print(thistuple[-4:-1])
使用len()方法可以计算出元祖中有多少个元素:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
元祖是不可变的,无法删除某个元素或全部元素,只能通过del关键字完全删除该元祖对象。
thistuple = ("apple", "banana", "cherry")
del thistuple
通过+号可以连接两个元祖,并返回一个新的元祖
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
tuple()构造方法可以创建一个元祖,或者将其他集合转换为元祖
thistuple = tuple(("apple", "banana", "cherry")) # 此处是两对括号
print(thistuple)
listtuple = tuple(["apple", "banana", "cherry"])
print(listtuple)