需求:統計串列list1中元素3的個數,并回傳每個元素的索引
list1 = [3, 3, 8, 9, 2, 10, 6, 2, 8, 3, 4, 5, 5, 4, 1, 5, 9, 7, 10, 2]
在實際工程中,可能會遇到以上需求,統計元素個數使用list.count()方法即可,不做多余說明
回傳每個元素的索引需要做一些轉換,簡單整理了幾個實作方法
1 list.index()方法
list.index()方法回傳串列中首個元素的索引,當有重復元素時,可以通過更改index()方法__start引數來更改起始索引
找到一個元素后,將起始索引替換為該元素的下一個索引,繼續進行查找,直到找到所有的元素索引
list1 = [3, 3, 8, 9, 2, 10, 6, 2, 8, 3, 4, 5, 5, 4, 1, 5, 9, 7, 10, 2]
count = list1.count(3)
index_list = []
index = -1
# 通過list.index()方法的__start引數,指定起始索引
for i in range(0, count):
index = list1.index(3, index + 1)
index_list.append(index)
print(index_list)
結果如下:

2 通過索引遍歷原串列,對每一個元素進行判斷
通過索引遍歷原串列,對每一個元素進行判斷,如果元素是目標元素,則回傳對應索引值,示例如下:
list1 = [3, 3, 8, 9, 2, 10, 6, 2, 8, 3, 4, 5, 5, 4, 1, 5, 9, 7, 10, 2]
list1_len = len(list1)
index_list = []
for i in range(0, list1_len):
if list1[i] == 3:
index_list.append(i)
print(index_list)
結果同上
3 enumerate()函式和串列推導式
使用enumerate()函式回傳可決議的index-value串列,然后使用串列推導式,同時使用if條件過濾得到目標值的索引,示例如下:
list1 = [3, 3, 8, 9, 2, 10, 6, 2, 8, 3, 4, 5, 5, 4, 1, 5, 9, 7, 10, 2]
index_list = [a for a, b in enumerate(list1) if b == 3]
print(index_list)
結果同上
各位大佬有好的實作方法可以在下方評論分享一下
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/283105.html
標籤:其他
