Python - 訪問列表項



訪問列表項

Python 中,一個 列表 是元素或物件的序列,即物件的排序集合。類似於陣列,列表中的每個元素都對應一個索引。

要訪問列表中的值,我們需要使用方括號 "[]" 表示法,並指定要檢索的元素的索引。

索引從第一個元素的 0 開始,每個後續元素遞增 1。列表中最後一項的索引始終是“長度-1”,其中“長度”表示列表中專案的總數。

除此之外,Python 還提供各種其他方法來訪問列表項,例如切片、負索引、從列表中提取子列表等。讓我們逐一瞭解一下:

使用索引訪問列表項

如上所述,要使用索引訪問列表中的項,只需在方括號 (“[]”) 中指定元素的索引,如下所示:

mylist[4] 

示例

以下是訪問列表項的基本示例:

list1 = ["Rohan", "Physics", 21, 69.75]
list2 = [1, 2, 3, 4, 5]

print ("Item at 0th index in list1: ", list1[0])
print ("Item at index 2 in list2: ", list2[2])

它將產生以下輸出:

Item at 0th index in list1: Rohan
Item at index 2 in list2: 3

使用負索引訪問列表項

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

我們還可以使用負整數表示列表末尾的位置來使用負索引訪問列表項。

示例

在下面的示例中,我們使用負索引訪問列表項:

list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]

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

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

Item at 0th index in list1: d
Item at index 2 in list2: True

使用切片運算子訪問列表項

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

[start:stop] 

其中,

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

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

示例

在下面的示例中,我們從 "list1" 中的索引 1 到最後檢索子列表,從 "list2" 中的索引 0 到 1 檢索子列表,並從 "list3" 中檢索所有元素:

list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]
list3 = ["Rohan", "Physics", 21, 69.75]

print ("Items from index 1 to last in list1: ", list1[1:])
print ("Items from index 0 to 1 in list2: ", list2[:2])
print ("Items from index 0 to index last in list3", list3[:])

以下是上述程式碼的輸出:

Items from index 1 to last in list1:  ['b', 'c', 'd']
Items from index 0 to 1 in list2:  [25.5, True]
Items from index 0 to index last in list3 ['Rohan', 'Physics', 21, 69.75]

從列表中訪問子列表

子列表是列表的一部分,它由原始列表中連續的元素序列組成。我們可以使用切片運算子和適當的起始和停止索引從列表中訪問子列表。

示例

在這個例子中,我們使用切片運算子從“list1”中索引“1到2”和從“list2”中索引“0到1”獲取子列表:

list1 = ["a", "b", "c", "d"]
list2 = [25.50, True, -55, 1+2j]

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

獲得的輸出如下:

Items from index 1 to 2 in list1: ['b', 'c']
Items from index 0 to 1 in list2: [25.5, True]
廣告