【Python】批量返回list匹配數據位置

通常情況下,在列表x中要查詢指定的數據可以使用x.index()來實現。但是,index函數只能返回頭一個出現的位置。爲此,實現一個批量返回出現位置的功能。略作記錄,以免以後需要重複造輪子。

x = [1, 2, 3, 4, 1, 2, 3, 5, 1, 2, 4, 6, 1]


def get_location_in_list(x, target):
    step = -1
    items = list()
    for i in range(x.count(target)):
        y = x[step + 1:].index(target)
        step = step + y + 1
        items.append(step)
    return items

print(get_location_in_list(x, 1))
# [0, 4, 8, 12]
print(get_location_in_list(x, 2))
# [1, 5, 9]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章