python - 元组
Python的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
- 创建元组
>>> tup1 = ('fd',123) >>> tup2 = () >>> tup1 ('fd', 123) >>> tup2 ()
无关闭分隔符
任意无符号的对象,以逗号隔开,默认为元组
>>> tup7 = 13,3,'yuanzu' >>> tup7 (13, 3, 'yuanzu')
-
访问元组
元组可以使用下标索引来访问元组中的值,如下实例:
>>> tup5 = ('23','mayun','dongzuo','mahuateng') >>> tup5[1] 'mayun' >>> tup5[1:3] ('mayun', 'dongzuo')
- 修改:不可以修改,但是两个元组可以连接生成一个新元组
>>> tup3 ('wangjinlin', 'lijiacheng') >>> tup5 ('23', 'mayun', 'dongzuo', 'mahuateng') >>> tup6 = tup3 +tup5 >>> tup6 ('wangjinlin', 'lijiacheng', '23', 'mayun', 'dongzuo', 'mahuateng')
-
删除:元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组
>>> tup6 ('wangjinlin', 'lijiacheng', '23', 'mayun', 'dongzuo', 'mahuateng') >>> del tup6 >>> tup6 Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'tup6' is not defined
-
元组运算符
与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。
Python 表达式 | 结果 | 描述 |
---|---|---|
len((1, 2, 3)) | 3 | 计算元素个数 |
(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 连接 |
('Hi!',) * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | 复制 |
3 in (1, 2, 3) | True | 元素是否存在 |
for x in (1, 2, 3): print x, | 1 2 3 | 迭代 |
-
元组内置函数Python元组包含了以下内置函数(与list差不多的函数)
1、cmp(tuple1, tuple2):比较两个元组元素。
2、len(tuple):计算元组元素个数。
3、max(tuple):返回元组中元素最大值。
4、min(tuple):返回元组中元素最小值。
5、tuple(seq):将列表转换为元组。
- 元组的方法
1.T.count(value) -> integer -- return number of occurrences of value
返回元组中包含指定元素的个数
>>> tup1 = (12,'mayuan','dongdong','xixi','mayuan') >>> tup1.count('mayuan') 2 >>> tup1.count('m') 0
2.T.index(value, [start, [stop]]) -> integer -- return first index of value
返回指定元素的第一个匹配的索引值
>>> tup1 (12, 'mayuan', 'dongdong', 'xixi', 'mayuan') >>> tup1.index('mayuan') 1 >>> tup1.index('mayuan',2,5) 4 >>> tup1.index('sb') #如果元组中不包含指定的元素,就报valueerror Traceback (most recent call last): File "<input>", line 1, in <module> ValueError: tuple.index(x): x not in tuple
end