Python元组
时间:2020-02-23 14:43:38 来源:igfitidea点击:
今天,我们将学习Python Tuple。
Python元组
Python元组是一系列Python对象。
他们很像列表。
但是元组和列表之间的区别在于,元组不能像我们可以更改列表的项一样进行更改。
元组也使用括号,而列表使用方括号。
Python元组是括号之间用逗号分隔的值的序列。
例如;
#an empty tuple emptyTup=() #tuple of string strTup=('This','is','a','tuple') #tuple of integers intTup=(1,2,3,4,5)
在Python元组中访问值
访问python元组中的值与访问列表中项目的方式非常相似。
通过索引号,我们可以访问元组中的值。
第一个元素的索引号为零,第二个元素的索引号为一,依此类推。
#tuple of string strTup=('This','is','a','tuple') #accessing first element print(strTup[0]) #accessing second element print(strTup[1]) #accessing fourth element print(strTup[3])
python中的元组还支持负索引,例如列表。
负索引表示该元组右边的索引号。
#tuple of string strTup=('This','is','a','tuple') #accessing first element from the right print(strTup[-1]) #accessing second element from the right print(strTup[-2]) #accessing second element from the right print(strTup[-4])
在Python Tuple中更新和删除
正如我们前面提到的,python中的元组不可更改。
因此,您不能更新单个元组元素。
但是我们可以采用两个元组并合并它们以创建一个新的元组。
同样,不可能删除单个元组元素。
虽然我们可以使用del
语句删除整个元组。
#tuple 1 tup1=(1,2,3) #tuple 2 tup2=(4,5) #tuple 3 tup3=tup1+tup2 print(tup3) #to delete tuple 1 del tup1 #this will show a traceback as tup1 is deleted. So it is not defined now print(tup1)
一些内置的Python Tuple函数
有一些内置函数可用于在python中操作元组。
看下面的代码以了解。
#a string tuple tup=('this','is','a','tuple') #len(tuple) gives total length of a tuple print(len(tup)) #max(tuple) gives maximum element of a tuple print(max(tup)) #min(tuple) gives minimum element of a tuple print(min(tup)) #count(x) gives number of occurances of x in the tuple print(tup.count('is')) #index(x) gives index of first occurances of x in the tuple print(tup.index('a'))