python 集合 元素 Tuple

元组(Tuple)

元组是有序且不可更改的集合。在 Python 中,元组是用圆括号编写的。

元组基础

#创建元组
thistuple=('apple','orange')
print(thistuple)#('apple', 'orange')

#访问tuple的项目
print(thistuple[1])#orange

#负索引表示从末尾开始,-1 表示最后一个项目,-2 表示倒数第二个项目,依此类推。
print(thistuple[-1])#orange

thattuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

#注释:搜索将从索引 2(包括)开始,到索引 5(不包括)结束。
print(thattuple[2:5])#('cherry', 'orange', 'kiwi')

#负索引范围
#如果要从元组的末尾开始搜索,请指定负索引:
#此例将返回从索引 -4(包括)到索引 -1(排除)的项目:
print(thattuple[-4:-1])#('orange', 'kiwi', 'melon')


#更改元组值(创建元组后,您将无法更改其值。元组是不可变的,或者也称为恒定的。)
#但是有一种解决方法。您可以将元组转换为列表,更改列表,然后将列表转换回元组。
x = ("apple", "banana", "cherry")
y=list(x)
y[1]='kiwi'
x=tuple(y)
print(x)#('apple', 'kiwi', 'cherry')


#for循环遍历元组
for x in thattuple:
    print(x)


#in 关键字 检测子项目是否存在在元组中
print('orange' in thattuple)#True

#len() 检车元组的长度
print(len(thattuple))#7
View Code

元组方法

#创建有一个项目的元组  必须在项目后面添加一个逗号;否则 Python 无法将变量识别为元组。
thistuple=('apple',)#这是元组
thattuple=('apple')#这不是元组
print(thistuple)#('apple')
print(thattuple)#apple


#删除项目您无法删除元组中的项目。

#元组是不可更改的,因此您无法从中删除项目,但您可以完全删除元组:
#del  关键字可以完全删除元组
del thistuple #完全删除

# print(thistuple) # 这会引发错误,因为元组已不存在。


#合并两个元组
#如需链接两个或多个元组,您可以使用+运算符
tuple1=('hello',)
tuple2=('world',)
tuple3=tuple1+tuple2
print(tuple3)#('hello', 'world')


#tuple() 构造函数   可以用来创建元组
tuple4=tuple(('apple','ios','p','p'))
print(tuple4)#('apple', 'ios')

#count(item)返回元组中指定值出现的次数
print(tuple4.count('ios'))#1

#index(item) 在元组中国搜索指定值 并返回它第一个被找到的位置
print(tuple4.index('p'))#2
View Code
原文地址:https://www.cnblogs.com/lvlisn/p/15121303.html