python - 如何找到列表中项目的索引,但不是完全匹配

标签 python python-3.x list indexing

我有一个这样的列表:

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/

相关文章:

java - 有效地将许多短排序列表合并成一个长排序列表

list - Haskell 中无限列表的笛卡尔积

python - 卡夫卡 : How to consume data based on Timestamp

python - Tkinter:如何限制用户使用多种功能

python - 为什么我的程序会这样做?

html - 拉伸(stretch)浏览器窗口时防止有序列表移动

python - 如何用python分割这个字符串?

python - word2vec算法可以使用tensorflow分布在多计算机上吗?

Python 过滤 *args **kwargs 中的参数

Python - 有没有办法将操作(+ - */)存储在列表中或作为变量?