我有一个这样的列表:
ls = ['item1', 'this is item2', 'item3']
我希望能够通过搜索 'item2'
找到项目 'this is item2'
的索引。 index 函数正在寻找精确匹配,因此它在这里无济于事:
index = ls.index('item2')
我怎样才能达到这个要求?
最佳答案
这是一个使用 next
和生成器的解决方案,并使用 enumerate
来获取索引:
>>> ls = ['item1', 'this is item2', 'item3']
>>> next(i for i, v in enumerate(ls) if 'item2' in v)
1
如果找不到该项目,它将引发 StopIteration
。如果您想要 None
或 -1
,您可以将它作为 next
的第二个参数:
>>> next((i for i, v in enumerate(ls) if 'item5' in v), -1)
-1
关于python - 如何找到列表中项目的索引,但不是完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59367379/