python 的元组操作
1,元组(tuple)
a,和列表几乎相同,也是一个数组,但是元组一旦创建,便不能修改,所以又叫只读列表
一般在配置文件中或者其他不希望修改的东西
b,任意无符号的对象,以逗号隔开,默认为元组,如下实例:
a=1,2,3,'e'
print (a)
输出:
a=(1,2,3,'e')
2,2个元组连接
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4") 2 name2=("一","二","三") 3 name3=name1+name2 4 print (name3) 5 6 输出: 7 ('1', '2', '3', '4', '一', '二', '三')
3,获取元组要素数量
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4") 2 n=len(name1) 3 print(n) 4 5 输出: 6 4
4,判断某个值是否在元组的要素中
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4") 2 y="3" in(name1) 3 print(y) 4 5 输出: 6 True
5,元组要素复制
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4") 2 name1=name1*4 3 print (name1) 4 5 输出: 6 ('1', '2', '3', '4', '1', '2', '3', '4', '1', '2', '3', '4', '1', '2', '3', '4')
6,元素的索引
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4") 2 print(name1[-1])#打印最后一个要素 3 print(name1[1])#打印第二个要素 4 print(name1[1:])#从第二个要素开始打印到最后一个要素 5 6 输出: 7 4 8 2 9 ('2', '3', '4')
7,获取元组要素的最大值,最小值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4") 2 max=max(name1) 3 min=min(name1) 4 print(max) 5 print(min) 6 7 输出: 8 4 9 1
8,转换列表为元组
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=["1","2","3","4"] 2 print (name1) 3 name2=tuple(name1) 4 print (name2) 5 6 输出: 7 ['1', '2', '3', '4'] 8 ('1', '2', '3', '4')
9,元组要素的枚举
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 for i in (1,2,3,4): 2 print (i) 3 4 输出: 5 1 6 2 7 3 8 4
10,枚举函数enumerate
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4") 2 for index,i in enumerate(name1): 3 print (index,i) 4 5 输出: 6 0 1 7 1 2 8 2 3 9 3 4
11,比较2个元组的元素
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import operator 2 name1=("1","2","3","4") 3 name2=("1","2","3","4") 4 y=operator.eq(name1[0],name2[0]) 5 n=operator.eq(name1[0],name2[1]) 6 print (y) 7 print (n) 8 9 输出: 10 True 11 False
注意:从python3.4.3开始cmp函数由于性能问题被去掉了,用operator库的.eq代替
12,元组的count方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4","1","1") 2 n=name1.count("1") 3 print (n) 4 5 输出: 6 3
13,元祖获取要素下标的方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 name1=("1","2","3","4","1","1") 2 n=name1.index("3") 3 print (n) 4 5 输出: 6 2