【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]

 

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