Python元组
元组
元组是一个集合是有序的和不可改变的。在Python中,元组带有圆括号。
访问元组项目
您可以通过在方括号内引用索引号来访问元组项:
负索引
负索引是指从头开始,-1
指的是最后一项,-2
指的是倒数第二项,
依此类推。
指标范围
您可以通过指定范围的起点和终点来指定索引范围。
指定范围时,返回值将是带有指定项目的新元组。
例
返回第三,第四和第五项:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
自己尝试»
注意:搜索将从索引2(包括)开始,到索引5(不包括)结束。
请记住,第一项的索引为0。
负指数范围
如果要从元组的末尾开始搜索,请指定负索引:
例
本示例将项目从索引-4(包括)返回到索引-1(排除)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
自己尝试»
更改元组值
创建元组后,您将无法更改其值。元组是不变的,或者也称为不变。
但是有一种解决方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。
例
将元组转换为列表即可进行更改:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x =
tuple(y)
print(x)
自己尝试»
通过元组循环
您可以使用循环来遍历元组项for
。
您将for
在“ Python For循环”一章中了解有关循环的更多信息。
检查项目是否存在
要确定元组中是否存在指定的项目,请使用in
关键字:
例
检查元组中是否存在“苹果”:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
自己尝试»
元组长度
要确定元组有多少个项目,请使用以下len()
方法:
新增项目
创建元组后,您将无法向其添加项目。元组是不变的。
例
您不能将项目添加到元组:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
自己尝试»
用一个项目创建元组
要创建仅包含一个项目的元组,您必须在该项目后添加逗号,否则Python不会将其识别为元组。
例
一个元组,记住逗号:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
自己尝试»
删除项目
注意:您不能删除元组中的项目。
元组不可更改,因此无法从中删除项目,但可以完全删除元组:
例
该del
关键字可以完全删除的元组:
thistuple = ("apple", "banana", "cherry")
del
thistuple
print(thistuple)
#this will raise an error because the tuple no longer exists
自己尝试»
加入两个元组
要连接两个或多个元组,可以使用+
运算符:
tuple()构造函数
也可以使用tuple()构造函数创建一个元组。
例
使用tuple()方法创建一个元组:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
自己尝试»
元组方法
Python有两个可在元组上使用的内置方法。
Method | Description |
---|---|
count() | Returns the number of times a specified value occurs in a tuple |
index() | Searches the tuple for a specified value and returns the position of where it was found |