Python 元組 Tuple

元組 Tuple 宣告

元組是用逗號分隔的一列值:

>>> t = 'a',1,'b',2,'c',3
>>> t
('a', 1, 'b', 2, 'c', 3)
>>> t = ('a',1,'b',2,'c',3)
>>> t
('a', 1, 'b', 2, 'c', 3)

 1. 元組是不可變的

 >>> t[0] = 'y'
Traceback (most recent call last):
  File "", line 1, in
TypeError: 'tuple' object does not support item assignment

 

但可將一個元組替換另一個元組,例如:

>>> t = 'a',1,'b',2,'c',3
>>> t
('a', 1, 'b', 2, 'c', 3)
>>> t = ('x',) + t[1:]
>>> t
('x', 1, 'b', 2, 'c', 3)
>>>

2. 元組賦值

>>> X = 2
>>> Y = 3
>>> X,Y = Y,X
>>> X
3
>>> Y
2

這樣的寫法很簡潔漂亮,而不是一般採用下列的寫法:

Z = X

X = Y

Y = Z

另一個例子是將一個字串拆解,分別賦值:

 >>> email_address = '[email protected]'
>>> name,company = email_address.split('@')
>>> name
'john'
>>> company
'company.com'

 3. 元組做為返回値

 >>> t = divmod(10,3)
>>> t
(3, 1)
>>> quot,rem = divmod(10,3)
>>> quot
3
>>> rem
1

 4. 可變長度參數元組

 >>> def print_all(*args):
...     print(args)
...
>>> print_all(1,2,3)
(1, 2, 3)
>>> print_all(1,2,3,4,5)
(1, 2, 3, 4, 5)

 

 >>> t = (10, 3)
>>> divmod(*t)
(3, 1)

 5. 列表與元組

>>> x = 'abc'
>>> y = '123'
>>> zip(x,y)


>>> id(x)
30795008
>>> id(y)
35332200


>>> for c in zip(x,y):
...     print(c)
...
('a', '1')
('b', '2')
('c', '3')


>>> list(zip(x,y))
[('a', '1'), ('b', '2'), ('c', '3')] 

 >>> t = [('a',1),('b',2),('c',3)]

>>> for letter,number in t:
...     print(letter,number)
...
a 1
b 2
c 3

 6. 字典與元組

 元組為一個列表,轉化為字典:

>>> t = [('a',1),('b',2),('c',3)]
>>> d = dict(t)
>>> d
{'a': 1, 'b': 2, 'c': 3}

 將字典以 items 方法,轉化為元組:

>>> m = d.items()
>>> m
dict_items([('a', 1), ('b', 2), ('c', 3)])

 以 zip 方法,快速創建字典:

>>> n = dict(zip('abc',range(3)))
>>> n
{'a': 0, 'b': 1, 'c': 2}

 

 

 

 

/end

 

你可能感兴趣的:(Python 元組 Tuple)