第七章、Python数据类型(tuple元组)
元组(tuple)
Python 中元组用圆括号 () 括起来的,其中的元素之间用逗号隔开。
1)元组的创建
>>> a=() #创建空元组
>>> type(a)
<type 'tuple'>
>>> b=(1)
>>> type(b)
<type 'int'>
>>> b=(1,) #创建元组时,元素的数量必须大于1,只有1个元素是整型int,不是元组型
>>> type(b)
<type 'tuple'>
>>> c=1,'q',[1,2] #多种数据类型组合在一起,是元组型
>>> type(c)
<type 'tuple'>
2)元组也是序列类型,也存在索引和切片操作
>>> c=1,'q',[1,2]
>>> type(c)
<type 'tuple'>
>>> c[1]
'q'
>>> c[2]
[1, 2]
>>> c[2][0] #单独提取元素中的小元素
1
>>> c[2][1]
2
3) 元组操作
元组中的元素不允许修改和删除,可以对元组进行拼接(+),也使用del语句来删除整个元组
>>> tup1 = (12, 34.56)
>>> tup2 = ('abc', 'xyz')
>>> tup1+tup2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
>>> tup1+tup2
(12, 34.56, 'abc', 'xyz')
>>> tup3=tup1+tup2
>>> tup3
(12, 34.56, 'abc', 'xyz')
>>> del tup3
>>> tup3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'tup3' is not defined
注:元组拼接的数据类型必须相同,否则拼接不成功。
>> tup1,tup2=(1,2,3),[2,'qw','c']
>>> tup3=list(tup1) #数据类型强制转换,转换成列表
>>> tup3+tup2
[1, 2, 3, 2, 'qw', 'c']

浙公网安备 33010602011771号