Python元組
Python有幾種順序的數據類型,可讓您以有組織的高效方式存儲數據集合。 基本序列類型是字符串,列表,元組和範圍對象。
本文將引導您了解Python元組的基礎知識。 我們將向您展示如何創建元組,訪問元素,解壓縮元組等等。
元組與列表相似,主要區別在於列表是可變的,而元組是不可變的。 這意味着創建後不能更改元組。
元組既可以存儲異構數據,也可以存儲同類數據,但通常用於存儲異構元素的集合。
創建元組
通過將項目放在一對圓括號中來創建元組 []
, 被逗號隔開。 它們可以具有任意數量的項目,這些項目可以是不同的類型。 這是一個例子:
colors = ('orange', 'white', 'green')
元組可以具有混合數據類型的項目。 您還可以聲明嵌套元組,其中更多的項是列表,元組或字典:
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))
圓括號之間沒有元素表示一個空的元組:
my_tuple = ()
要創建僅包含一個元素的元組,必須在該元素後添加一個逗號:
my_tuple = (1)
type(my_tuple)
my_tuple = (1,)
type(my_tuple)
<class 'int'>
<class 'tuple'>
元組也可以使用 tuple()
構造函數:
colors_list = ['orange', 'white', 'green']
colors_typle = tuple(colors_list)
print(type(colors_typle))
<class 'tuple'>
構造元組的另一種方法是使用元組打包功能,該功能允許您從一系列用逗號分隔的對象中創建元組:
directions = "North", "South", "East", "West"
print(type(directions))
<class 'tuple'>
訪問元組元素
元組項目可以通過其索引引用。 索引是整數,從 0
至 n-1
哪裡 n
是項目數:
my_tuple = ["a", "b", "c", "d"]
0 1 2 3
在Python中,索引用方括號指定:
my_tuple[index]
例如,訪問元組的第三個元素,您將 tuple_name[2]
:
directions = ("North", "South", "East", "West")
directions[2]
'East'
如果您引用的索引不存在, IndexError
引發異常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
要訪問嵌套元組中的項目,請使用多個索引:
my_tuple = (1, False, ["red", "blue"], ("foo", "bar"))
my_tuple[3][1]
'bar'
您還可以使用負索引訪問元組元素。 最後一項稱為 -1
,倒數第二個項目為 -2
等等:
my_tuple = ("a", "b", "c", "d")
-4 -3 -2 -1
directions = ("North", "South", "East", "West")
directions[-2]
'East'
切片元組
在Python中,您可以使用以下形式對元組和其他順序數據類型進行切片:
sequence[start:stop:step]
start
是提取開始的索引。 當使用負索引時,它表示從元組末尾的偏移量。 如果省略此參數,則切片從索引0開始。stop
是結束提取之前的索引; 結果不包含“停止”元素。 當使用負索引時,它表示從元組末尾的偏移量。 如果省略此參數或大於元組的長度,則切片將轉到元組的末尾。step
是一個可選參數,它指定切片的步驟。 未指定時,默認值為1。如果使用負值,則切片將採用相反的順序獲取元素。
切片元組的結果是包含提取的元素的新元組。
以下形式在Python中是合法的:
T[:] # copy whole tuple
T[start:] # slice the tuple starting from the element with index "start" to the end of the tuple.
T[:stop] # slice the tuple starting from the begging up to but not including the element with index "stop".
T[start:stop] # slice the tuple starting from the element with index "start" up to but not including the element with index "stop".
stop"
T[::step] # slice the tuple with a stride of "step"
下面是一個示例,該示例如何切片從索引為1的元素開始到但不包括索引為4的元素的元組:
vegetables = ('Potatoes', 'Garlic', 'Celery', 'Carrots', 'Broccoli')
vegetables[1:4]
('Garlic', 'Celery', 'Carrots')
打開元組包裝
Python功能中的序列解壓縮,使您可以將分配序列對象分配給變量。 這是一個例子:
colors = ('orange', 'white', 'green')
a, b, c = colors
print(a)
print(b)
print(c)
根據其位置將元組元素的值分配給左側的變量:
orange
white
green
打開元組的包裝時,左側元組上的變量數必須與元組元素的數相同。 否則,您會得到一個 ValueError
例外。
colors = ('orange', 'white', 'green')
a, b = colors
ValueError: too many values to unpack (expected 2)
當方法或函數返回對象序列時,解壓縮很方便:
def square_area_circumference(side_lenght):
return side_lenght * side_lenght, side_lenght * 4
area, circumference = square_area_circumference(5)
print(area)
print(circumference)
25
20
更改元組
由於元組是不可變的數據結構,因此我們無法直接更新它們。 您不能添加,更改,刪除元組中的元素。
如果您嘗試更改元組元素,則會得到 TypeError
例外:
colors = ("orange", "white", "green")
colors[1] = "blue"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
可變元組項的元素可以更改。 例如,如果元組將列表作為其元素之一,則可以更新列表元素:
my_tuple = (1, 2, [5, 6, 7])
my_tuple[2][1] = 4
print(my_tuple)
(1, 2, [5, 4, 7])
元組長度
內建 len()
函數返回給定對象的項目總數。
要查找元組的長度,請將其作為參數傳遞給 len()
功能:
len(L)
這是一個例子:
colors = ("orange", "white", "green")
lenght = len(colors)
print(lenght)
3
通過元組迭代
要遍曆元組中的所有元素,可以使用 for
循環:
directions = ("North", "South", "East", "West")
for direction in directions:
print(direction)
North
South
East
West
如果需要索引,則可以使用幾種方法。 最常見的方法是將 range()
和 len()
功能或使用內置 enumerate()
功能。
下面的示例顯示如何檢索元組中每個項目的索引和值:
directions = ("North", "South", "East", "West")
for i in range(len(directions)):
print("Index {} : Value {}".format(i, directions[i]))
Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West
而不是使用 range(len(...))
模式,您可以使用 enumerate()
函數以更Python化的方式遍曆元組:
directions = ("North", "South", "East", "West")
for index, value in enumerate(directions):
print("Index {} : Value {}".format(index, value))
Index 0 : Value North
Index 1 : Value South
Index 2 : Value East
Index 3 : Value West
檢查元素是否存在
要檢查元組中是否存在元素,可以使用 in
和 not in
運營商:
colors = ("orange", "white", "green")
print("orange" in colors)
輸出將是 True
要麼 False
:
True
這是使用 if
聲明:
colors = ("orange", "white", "green")
if "blue" not in colors:
print("no")
else:
print("yes")
no
元組方法
元組對象接受以下方法:
count(x)
-返回“ x”出現在元組中的次數。index(x)
-返回值為“ x”的元素首次出現的位置。
以下是顯示如何使用方法的簡單示例:
my_tuple = ("a", "s", "s", "q", "a", "n")
print(my_tuple.count('a'))
print(my_tuple.index('a'))
2
0
結論#
在Python中,元組是對象的不變序列,一旦創建就無法更改。
如果您有任何問題或反饋,請隨時發表評論。
蟒蛇