python中的元组(tuple)
- 元组的基本概念及常规操作
元组的创建:
列表:打了激素的数组
元组:带了紧箍咒的列表。不可变的数据类型,没有增删改,可以存储任意数据类型。
定义一个元组:
a= (1,1.2,True,'westos')
注意元组和列表的不同
元组的修改
注意:元组本身不可修改,如果元组里包含可变的数据类型,可以间接修改。
a = ([1,2,3],7,8,9)
print(a,type(a))
a[0].append(4)
print(a)
列表元组之间的转换
a = (1,2,3)
b = [4,5,6]
print(a,type(a))
print(b,type(b))
c=list(a)
d=tuple(b)
print(c,type(c))
print(d,type(d))
另外:元组只有一个元素的时候,元素后一定要加逗号,否则数据类型不确定
查找元组中元素的位置和统计元素出现的次数
a = (1, 5, True, 'westos','westos')
print(a.index('westos')) # 查找westos最先出现的位置
print(a.count('westos')) # 统计westos出现的次数
2.元组的特性
元组的索引、切片、重复、连接
定义一个元组:
a = (1, 5, True, 'westos','westos')
索引:
print(a[0])
print(a[3])
切片:
print(a[0:2])
print(a[::-1])
print(a[:-1])
重复:
print(a*2)
连接:
a = (1, 5, True, 'westos','westos')
b = ('DNS',888)
print(a+b)
元组的成员操作符、for循环(迭代)、枚举,zip压缩
成员操作符:
a = (1, 5, True, 'westos','westos')
b = ('DNS',888)
print('westos' in a)
print(1 in a)
print('DNS' not in b)
print('westos' not in b)
for循环(迭代):
a = (1, 5, True, 'westos','westos')
for i in a:
print(i)
枚举:
返回索引值和对应的value值
a = (1, 5, True, 'westos','westos')
for i,v in enumerate(a):
print(i,'---',v)
zip压缩:
a = (1, 5, True, 'westos','westos')
b=('我','爱','你','中','国')
for i in zip(a,b):
print(i)