Python list index lambda - 在列表中查找项目的索引

Python find all index of item in list / python / list / indexing

给定一个列表 ["foo", "bar", "baz"] 和列表 "bar" 中的一个项目,如何在Python中获取其索引( 1 )?

Georgy



Answer #1

| 指数(...)
| L.index(value,[start,[stop]])->整数-返回值的第一个索引

def all_indices(value, qlist):
    indices = []
    idx = -1
    while True:
        try:
            idx = qlist.index(value, idx+1)
            indices.append(idx)
        except ValueError:
            break
    return indices

all_indices("foo", ["foo","bar","baz","foo"])