跳到內容

Python 程式設計/元組

來自華夏公益教科書,開放的書籍,開放的世界


Python 中的元組與列表非常相似,區別在於元組一旦建立就是不可變的(不可更改)。可雜湊物件的元組是可雜湊的,因此適合作為字典中的鍵和集合中的成員。

Python 中的元組一覽

tup1  = (1, 'a')
tup2  = 1, 'a'                # Brackets not needed
tup3  = (1,)                  # Singleton tuple
tup4  = 1,                    # Singleton tuple without brackets
tup5 = ()                     # Empty tuple
list1 = [1, 'a']
it1, it2 = tup1               # Assign items by "value unpacking"
print(tup1 == tup2)           # True
print(tup1 is tup2)           # False
print(tup1 == list1)          # False
print(tup1 == tuple(list1))   # True
print(list(tup1) == list1)    # True
print(tup1[0])                # First member
for item in tup1: print(item) # Iteration
print((1, 2) + (3, 4))        # (1, 2, 3, 4)
print(tup1 * 2)               # (1, 'a', 1, 'a')
tup1 += (3,)                  # Tuple and string concatenation work similarly
print(tup1)                   # (1, 'a', 3), despite immutability *

# * From docs: "For immutable targets such as strings, numbers, and tuples,
# the updated value is computed, but not assigned back to the input variable."

print(len(tup1))              # Item count
print(3 in tup1)              # Membership - True
tup6 = ([1,2],)
tup6[0][0]=3
print(tup6)                   # The list referred to by a tuple remains mutable
set1 = set( (1,2) )           # Can be placed into a set
#set1 = set( ([1,2], 2) )     # Error: The list within makes it unhashable
def foo():
    return 6, 9               # Return multiple values, as a tuple
r1, r2 = foo()                # Receive multiple values
print(f'r1 is {r1}, r2 is {r2}')

元組表示法

[編輯 | 編輯原始碼]

元組可以直接建立,也可以從列表轉換。通常,元組用括號括起來。

>>> l = [1, 'a', [6, 3.14]]
>>> t = (1, 'a', [6, 3.14])
>>> t
(1, 'a', [6, 3.14])
>>> tuple(l)
(1, 'a', [6, 3.14])
>>> t == tuple(l)
True
>>> t == l
False

一個元素的元組是用括號中的元素後跟一個逗號來建立

>>> t = ('A single item tuple',)
>>> t
('A single item tuple',)

此外,元組將由用逗號分隔的元素建立。

>>> t = 'A', 'tuple', 'needs', 'no', 'parens'
>>> t
('A', 'tuple', 'needs', 'no', 'parens')

打包和解包

[編輯 | 編輯原始碼]

您還可以使用元組執行多重賦值。

>>> article, noun, verb, adjective, direct_object = t   #t is defined above
>>> noun
'tuple'

請注意,賦值運算子的兩側,或者兩側都可以包含元組。

>>> a, b = 1, 2
>>> b
2

上面的例子:article, noun, verb, adjective, direct_object = t 被稱為“元組解包”,因為元組t 被解包,其值被分配給左側的每個變數。“元組打包”是相反的:t=article, noun, verb, adjective, direct_object。解包元組或執行多重賦值時,分配的變數數量必須與分配的值數量相同。

元組運算

[編輯 | 編輯原始碼]

這些與列表相同,除了我們不能分配給索引或切片,並且沒有“append”運算子。

>>> a = (1, 2)
>>> b = (3, 4)
>>> a + b
(1, 2, 3, 4)
>>> a
(1, 2)
>>> b
(3, 4)
>>> a.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'append'
>>> a
(1, 2)
>>> a[0] = 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
>>> a
(1, 2)

對於列表,我們將有

>>> a = [1, 2]
>>> b = [3, 4]
>>> a + b
[1, 2, 3, 4]
>>> a
[1, 2]
>>> b
[3, 4]
>>> a.append(3)
>>> a
[1, 2, 3]
>>> a[0] = 0
>>> a
[0, 2, 3]

元組屬性

[編輯 | 編輯原始碼]

長度:查詢元組的長度與列表相同;使用內建的 len() 方法。

>>> len( ( 1, 2, 3) )
3
>>> a = ( 1, 2, 3, 4 )
>>> len( a )
4

使用內建的 tuple() 方法將列表轉換為元組。

>>> l = [4, 5, 6]
>>> tuple(l)
(4, 5, 6)

使用內建的 list() 方法將元組轉換為列表,以將其強制轉換為列表

>>> t = (4, 5, 6)
>>> list(t)
[4, 5, 6]

字典也可以使用字典的 items 方法轉換為元組對的元組

>>> d = {'a': 1, 'b': 2}
>>> tuple(d.items())
(('a', 1), ('b', 2))

元組的用途

[編輯 | 編輯原始碼]

元組可以用在列表代替的位置,其中專案的數量已知且較小,例如,從函式返回多個值時。許多其他語言需要建立物件或容器來返回,但使用 Python 的元組賦值,多值返回很容易

def func(x, y):
    # code to compute x and y
    return x, y

這個生成的元組可以使用上面解釋的元組賦值技術輕鬆解包

x, y = func(1, 2)

使用列表推導處理元組元素

[編輯 | 編輯原始碼]

有時需要操縱元組中包含的值以建立新的元組。例如,如果我們想找到一種方法來使元組中的所有值翻倍,我們可以結合上面的一些資訊以及列表推導,如下所示

def double(T):
    'double() - return a tuple with each tuple element (e) doubled.'
    return tuple( [ e * 2 for e in T ] )
  1. 建立列表 ['a', 'b', 'c'],然後從該列表建立元組。
  2. 建立元組 ('a', 'b', 'c'),然後從該元組建立列表。(提示:完成此操作所需的材料已介紹,但並不完全明顯)
  3. 同時進行以下例項化:a = 'a', b=2, c='gamma'。(也就是說,在一行程式碼中)。
  4. 建立一個只包含一個元素的元組,該元素又包含三個元素 'a'、'b' 和 'c'。使用 len() 函式驗證長度實際上為 1。
[編輯 | 編輯原始碼]
華夏公益教科書