Python - 訪問元組元素



訪問元組元素

訪問Python元組中值的常用方法是使用索引。我們只需要在方括號[]表示法中指定要檢索的元素的索引。

在Python中,一個元組是不可變的有序元素集合。“不可變”意味著一旦建立了元組,就不能修改或更改其內容。我們可以使用元組將相關的數 據元素組合在一起,類似於列表,但關鍵區別在於元組是不可變的,而列表是可變的。

除了索引之外,Python還提供各種其他方法來訪問元組專案,例如切片、負索引、從元組中提取子元組等等。讓我們逐一介紹:

使用索引訪問元組元素

元組中的每個元素都對應一個索引。第一個元素的索引從0開始,後續每個元素的索引遞增1。元組中最後一個元素的索引始終是“長度-1”,其中“長度”表示元組中元素的總數。要訪問元組的元素,我們只需要指定要訪問/檢索的元素的索引,如下所示:

tuple[3] 

示例

以下是使用切片索引訪問元組元素的基本示例:

tuple1 = ("Rohan", "Physics", 21, 69.75)
tuple2 = (1, 2, 3, 4, 5)

print ("Item at 0th index in tuple1: ", tuple1[0])
print ("Item at index 2 in tuple2: ", tuple2[2])

它將產生以下輸出:

Item at 0th index in tuple1:  Rohan
Item at index 2 in tuple2:  3

使用負索引訪問元組元素

Python中的負索引用於訪問元組末尾的元素,其中-1表示最後一個元素,-2表示倒數第二個元素,依此類推。

我們也可以使用負整數表示從元組末尾開始的位置,透過負索引訪問元組項。

示例

在下面的例子中,我們使用負索引訪問元組項:

tup1 = ("a", "b", "c", "d")
tup2 = (25.50, True, -55, 1+2j)

print ("Item at 0th index in tup1: ", tup1[-1])
print ("Item at index 2 in tup2: ", tup2[-3])

我們得到如下所示的輸出:

Item at 0th index in tup1:  d
Item at index 2 in tup2:  True

使用負索引訪問元組項的範圍

元組項的範圍是指使用切片訪問元組中元素的子集。因此,我們可以使用 Python 中的切片操作,透過負索引訪問元組項的範圍。

示例

在下面的例子中,我們使用負索引訪問元組項的範圍:

tup1 = ("a", "b", "c", "d")
tup2 = (1, 2, 3, 4, 5)

print ("Items from index 1 to last in tup1: ", tup1[1:])
print ("Items from index 2 to last in tup2", tup2[2:-1])

它將產生以下輸出:

Items from index 1 to last in tup1: ('b', 'c', 'd')
Items from index 2 to last in tup2: (3, 4)

使用切片運算子訪問元組項

Python 中的切片運算子用於從元組中獲取一個或多個項。我們可以透過指定要提取的索引範圍來使用切片運算子訪問元組項。它使用以下語法:

[start:stop] 

其中,

  • start 是起始索引(包含)。
  • stop 是結束索引(不包含)。

示例

在下面的例子中,我們從 "tuple1" 中檢索從索引 1 到最後的子元組,從 "tuple2" 中檢索索引 0 到 1 的子元組,並檢索 "tuple3" 中的所有元素:

tuple1 = ("a", "b", "c", "d")
tuple2 = (25.50, True, -55, 1+2j)
tuple3 = (1, 2, 3, 4, 5)
tuple4 = ("Rohan", "Physics", 21, 69.75)

print ("Items from index 1 to last in tuple1: ", tuple1[1:])
print ("Items from index 0 to 1 in tuple2: ", tuple2[:2])
print ("Items from index 0 to index last in tuple3", tuple3[:])

以上程式碼的輸出如下:

Items from index 1 to last in tuple1:  ('b', 'c', 'd')
Items from index 0 to 1 in tuple2:  (25.5, True)
Items from index 0 to index last in tuple3 ('Rohan', 'Physics', 21, 69.75)

從元組中訪問子元組

子元組是元組的一部分,它包含原始元組中連續的元素序列。

我們可以使用切片運算子和適當的起始和結束索引從元組中訪問子元組。它使用以下語法:

my_tuple[start:stop]

其中,

  • start 是起始索引(包含)。
  • stop 是子元組的結束索引(不包含)。

如果我們不提供任何索引,切片運算子預設為從索引 0 開始,到元組中的最後一項結束。

示例

在這個例子中,我們使用切片運算子從 "tuple1" 中獲取索引 "1 到 2" 的子元組,從 "tuple2" 中獲取索引 "0 到 1" 的子元組:

tuple1 = ("a", "b", "c", "d")
tuple2 = (25.50, True, -55, 1+2j)

print ("Items from index 1 to 2 in tuple1: ", tuple1[1:3])
print ("Items from index 0 to 1 in tuple2: ", tuple2[0:2])

獲得的輸出如下:

Items from index 1 to 2 in tuple1:  ('b', 'c')
Items from index 0 to 1 in tuple2:  (25.5, True)
廣告