1.一個(gè)賦值---所謂"元"組,就是"圓括號(hào)"
>>> a="abc",123,['name','age']
>>> a
('abc', 123, ['name', 'age'])
>>> type(a)
# 這就是元組
<class 'tuple'>
- 特點(diǎn):不可修改,實(shí)際上是一個(gè)融合列表和字符串的雜交產(chǎn)物
# 重新賦值是不行的,但可以轉(zhuǎn)為列表后,再修改
>>> a[0]='def'
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a[0]='def'
TypeError: 'tuple' object does not support item assignment
>>> a.append('Jim Green')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
a.append('Jim Green')
AttributeError: 'tuple' object has no attribute 'append'
>>>
2.單個(gè)元素的注意事項(xiàng)---末尾要加逗號(hào)
>>> a=(2)
>>> type(a)
<class 'int'>
>>> b=(2,)
>>> type(b)
<class 'tuple'>
3.列表和元組之間的轉(zhuǎn)換---list()和tuple():
>>> tuple1=(1,2,3,4,5)
>>> list1=list(tuple1)
>>> list1
[1, 2, 3, 4, 5]
>>> tuple2=tuple(list1)
>>> tuple2
(1, 2, 3, 4, 5)
# 值一樣,但是不是同一個(gè)對(duì)象
>>> tuple1 is tuple2
False
>>> id(tuple1)
44426432
>>> id(tuple2)
51184128