带了紧箍咒的列表
元组和列表不同在于元组为不可变数据类型,它没有append等方法,存储数据更安全
tu=(1,2,3,4)
注:单个元组定义必须在后面加逗号,如tu=(1,)
工厂方法:t=tuple([1,2,3])
元组也属于序列:
支持索引、切片、拼接、重复、成员操作符
In [14]: t=(‘1‘,‘2‘,‘3‘)*2 In [15]: t Out[15]: (‘1‘, ‘2‘, ‘3‘, ‘1‘, ‘2‘, ‘3‘) In [17]: t1=(‘hello‘,‘one‘) In [18]: t2=(‘hello‘,‘two‘) In [19]: t1 + t2 Out[19]: (‘hello‘, ‘one‘, ‘hello‘, ‘two‘)
元组特性:
对元组分别赋值,引申对多个变量也可以通过元组方式分别赋值
In [20]: t=(‘vaon‘,‘10‘,‘male‘) In [21]: name,age,gender = t In [23]: print name,age,gender vaon 10 male
修改元组:
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
In [33]: t1=(1,2,3) In [34]: t2=(‘a‘,‘b‘,‘c‘) In [35]: t3 = t1 + t2 In [36]: print t3 (1, 2, 3, ‘a‘, ‘b‘, ‘c‘)
删除元组:
元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组
In [30]: t = (‘ecs‘,‘evs‘,‘vbs‘) In [31]: del t In [32]: print t --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-32-72ca88a82da5> in <module>() ----> 1 print t NameError: name ‘t‘ is not defined
t.index(value)
返回value在元组中的偏移量(即索引值)
实例:在t元组中索引2~7之间,打印出值为bool类型的元素的索引值
#!/usr/bin/env python # coding:utf-8 t=(1,2,3,4,True,False,‘a‘,[1,2,3]) for i in t: if type(i) == bool: print t.index(i,2,7)
执行结果:
[root@centos01 python]# python check_bool.py 4 5
t.count(value)-->int
返回value在元组中出现的次数
cmp
len
max
min
enumerate
zip
原文:https://www.cnblogs.com/vaon/p/10972383.html