Python 编程语言中有四种集合数据类型:
选择集合类型时,了解该类型的属性很有用。
为特定数据集选择正确的类型可能意味着保留含义,并且可能意味着提高效率或安全性
列表:用方括号编写
alist = ["apple","banana","cherry"]
元组:用圆括号编写
blist=("apple","banana","cherry")
创建元组后,您将无法更改其值。元组是不可变的,或者也称为恒定的。
但是有一种解决方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。
把元组转换为列表即可进行更改:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
您可以使用 for 循环遍历元组项目。
遍历项目并打印值:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
要确定元组中是否存在指定的项,请使用 in 关键字:
检查元组中是否存在 "apple":
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
要确定元组有多少项,请使用 len() 方法:
打印元组中的项目数量:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
元组一旦创建,您就无法向其添加项目。元组是不可改变的。
您无法向元组添加项目:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # 会引发错误
print(thistuple)
如需创建仅包含一个项目的元组,您必须在该项目后添加一个逗号,否则 Python 无法将变量识别为元组。
单项元组,别忘了逗号:
thistuple = ("apple",)
print(type(thistuple))
#不是元组
thistuple = ("apple")
print(type(thistuple))
注释:您无法删除元组中的项目。
元组是不可更改的,因此您无法从中删除项目,但您可以完全删除元组:
del 关键字可以完全删除元组:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) # 这会引发错误,因为元组已不存在
如需连接两个或多个元组,您可以使用 + 运算符:
合并这个元组:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
也可以使用 tuple() 构造函数来创建元组。
使用 tuple() 方法来创建元组:
thistuple = tuple(("apple", "banana", "cherry")) # 请注意双括号
print(thistuple)