Python元组
mytuple = ("apple", "banana", "cherry")
元组是有序且不可更改的集合。
元组项
元组项是有序的、不可更改的,并且允许重复值。
元组项被索引,第一项具有索引[0],第二项具有索引[1]等。
已订购
当我们说元组是有序的时,这意味着项目具有定义的顺序,并且该顺序不会改变。
不可改变的
元组是不可更改的,这意味着在创建元组后我们不能更改、添加或删除项目。
允许重复
由于元组被索引,它们可以有具有相同值的项目:
元组项 - 数据类型
元组项可以是任何数据类型:
tuple1 = ("abc", 34, True, 40, "male")
类型()
从 Python 的角度来看,元组被定义为数据类型为“元组”的对象:
<class 'tuple'>
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
tuple() 构造函数
也可以使用tuple()构造函数来创建一个元组。
使用 tuple() 方法创建一个元组:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
访问元组项
您可以通过引用方括号内的索引号来访问元组项:
例子
打印元组中的第二项:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
添加项目
由于元组是不可变的,它们没有内置 append()方法,但还有其他方法可以将项目添加到元组。
1.转换为列表:就像更改元组的解决方法一样,您可以将其转换为列表,添加您的项目,然后将其转换回元组。
例子
将元组转换为列表,添加“橙色”,然后将其转换回元组:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
2.将元组添加到元组。您可以将元组添加到元组中,因此如果您想添加一个(或多个)项目,请使用这些项目创建一个新元组,并将其添加到现有元组中:
创建一个值为“orange”的新元组,并添加该元组:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
删除项目
注意:您不能删除元组中的项目。
元组是不可更改的,因此您不能从中删除项目,但您可以使用与我们用于更改和添加元组项目相同的解决方法:
将元组转换为列表,删除“apple”,并将其转换回元组:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
或者您可以完全删除元组:
del关键字可以完全删除元组:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
解包元组
当我们创建一个元组时,我们通常给它赋值。这称为“打包”一个元组:
打包一个元组:
fruits = ("apple", "banana", "cherry")
但是,在 Python 中,我们也可以将值提取回变量中。这称为“解包”:
例子
解包元组:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
使用星号*
如果变量的数量小于值的数量,您可以*在变量名称中添加一个,并且值将作为列表分配给变量:
例子
将其余的值分配为一个名为“red”的列表:
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
如果星号被添加到另一个变量名而不是最后一个,Python 将为变量分配值,直到剩余的值的数量与剩余的变量的数量相匹配。
例子
添加“tropic”变量的值列表:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
循环遍历一个元组
您可以使用循环遍历元组项for。
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
for i in range(len(thistuple)):
print(thistuple[i])
i = 0
while i < len(thistuple):
print(thistuple[i])
i = i + 1
加入两个元组
要连接两个或多个元组,您可以使用+ 运算符:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
将元组相乘
如果要将元组的内容乘以给定次数,可以使用* 运算符:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
元组count()方法
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
#返回值 5 在元组中出现的次数,该count()方法返回指定值在元组中出现的次数。tuple.count(value)
index()方法
x = thistuple.index(8)
#搜索值 8 的第一次出现,并返回其位置
浙公网安备 33010602011771号