1,元组(tuple)
a,和列表几乎相同,也是一个数组,但是元组一旦创建,便不能修改,所以又叫只读列表
一般在配置文件中或者其他不希望修改的东西
b,任意无符号的对象,以逗号隔开,默认为元组,如下实例:
a=1,2,3,'e'
print (a)
输出:
a=(1,2,3,'e')
2,2个元组连接
1 name1=("1","2","3","4")
2 name2=("一","二","三")
3 name3=name1+name2
4 print (name3)
5
6 输出:
7 ('1', '2', '3', '4', '一', '二', '三')
2个元组合并
3,获取元组要素数量
1 name1=("1","2","3","4")
2 n=len(name1)
3 print(n)
4
5 输出:
6 4
获取元组要素数量
4,判断某个值是否在元组的要素中
1 name1=("1","2","3","4")
2 y="3" in(name1)
3 print(y)
4
5 输出:
6 True
某个值在元组中是否存在
5,元组要素复制
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,元素的索引
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,获取元组要素的最大值,最小值
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,转换列表为元组
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,元组要素的枚举
1 for i in (1,2,3,4):
2 print (i)
3
4 输出:
5 1
6 2
7 3
8 4
元组要素的枚举
10,枚举函数enumerate
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
enumerate函数
11,比较2个元组的元素
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方法
1 name1=("1","2","3","4","1","1")
2 n=name1.count("1")
3 print (n)
4
5 输出:
6 3
元组的count方法
13,元祖获取要素下标的方法
1 name1=("1","2","3","4","1","1")
2 n=name1.index("3")
3 print (n)
4
5 输出:
6 2
获取要素下标