Python标准库用C实现了丰富的序列类型:
本篇介绍的是元组!!!
1、元组定义
元组(tuple)是由 ’()‘ 括起来的一组数据,其中可包含各种不同的数据类型,值得注意的是,元组一旦创建,其内容边不可修改,因此,元组不能进行增、删、改操作,当元组中只有一个元素时,必须在元素后加 ‘ ,’。
>>> t = (2)
>>> t
2
>>> type(t)
<class 'int'>
>>> t = (2,)
>>> type(t)
<class 'tuple'>
>>> t = (1,2,3,4)
>>> t
(1, 2, 3, 4)
2、元组自带函数
index() : 返回元素第一次出现的位置下标,若没有该元素,则报错;
count() : 指定元素出现的次数;
>>> t = (1,2,3,4,2,3,4)
>>> t.index(2)
1
>>> t.count(3)
2
3、系统函数
max() : 返回元组中元素的最大值(元组中元素必须为同一种数据类型);
min() : 返回元组中元素的最小值(元组中元素必须为同一种数据类型);
sum() : 对元组中的元素进行求和操作(元组中元素必须为整型);
len() : 获取元组的长度;
sorted() : 对元组进行升序排序,结果保存为列表类型(元组中元素必须为同一种数据类型);
>>> t1 = (3,2,6,5,8,9,0,1,4)
>>> t2 = ('aa','bb','cc','dd')
>>> max(t1)
9
>>> max(t2)
'dd'
>>> sum(t1)
38
>>> sum(t2)
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
sum(t2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> len(t1)
9
>>> sorted(t1)
[0, 1, 2, 3, 4, 5, 6, 8, 9]
4、符号
* 、+、is、is not、in、not in
>>> t1 = (1,2,3)
>>> t2 = (4,5,6)
>>> t1 * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> t1
(1, 2, 3)
>>> t1 + t2
(1, 2, 3, 4, 5, 6)
>>> 2 in t1
True
>>> t3 = t1
>>> t1 is t3
True