通常情況下,在列表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]