- 元组
定义:Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。
注:如只写小括号但括号中没有逗号则不是元组。
- 创建、重复、连接:
>>> tup2 = () #创建空元组
>>> type(tup2)
<class 'tuple'>
>>> tup1 = (12,'a',['999','xyz'],7-9j,{'a':10}) #创建
>>> tup1
(12, 'a', ['999', 'xyz'], (7-9j), {'a': 10})
>>> tup1 *2 #重复
(12, 'a', ['999', 'xyz'], (7-9j), {'a': 10}, 12, 'a', ['999', 'xyz'], (7-9j), {'a': 10})
>>> tup1 + ((1,2,3),4,5,6,None,8) #连接
(12, 'a', ['999', 'xyz'], (7-9j), {'a': 10}, (1, 2, 3), 4, 5, 6, None, 8)
>>> typ3 = (8) #只写小括号但括号中没有逗号则不是元组。
>>> type(typ3)
<class 'int'>
- 访问元组:
- 切片访问:
>>> tup1[:]
(12, 'a', ['999', 'xyz'], (7-9j), {'a': 10})
>>> tup1[1]
'a'
>>> tup1[3:]
((7-9j), {'a': 10})
>>> tup1[:3]
(12, 'a', ['999', 'xyz'])
- 成员关系操作:
>>> '999' in tup1
False
>>> ['999', 'xyz'] in tup1
True
- 修改元组:
- 元组中元素是不能修改的
>>> tup1
(12, 'a', ['999', 'xyz'], (7-9j), {'a': 10})
>>> tup1['a'] = 'abcd'
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
tup1['a'] = 'abcd'
TypeError: 'tuple' object does not support item assignment
- 可以修改元组中列表、字典的元素
>>> tup1
(12, 'a', ['999', 'xyz'], (7-9j), {'a': 10})
>>> tup1[2][0] = 888
>>> tup1
(12, 'a', [888, 'xyz'], (7-9j), {'a': 10})
>>> tup1[4][0] = 777
>>> tup1
(12, 'a', [888, 'xyz'], (7-9j), {'a': 10, 0: 777})
- 删除元组:
- 元组中的元素不能单独被删除
>>> tup1
(12, 'a', [888, 'xyz'], (7-9j), {'a': 10, 0: 777})
>>> del tup1[1]
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
del tup1[1]
TypeError: 'tuple' object doesn't support item deletion
- 可以删除整个元组
>>> del tup1
>>> tup1
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
tup1
NameError: name 'tup1' is not defined