python - 在 Python 中,如何找到给定列表的子项的索引?

标签 python list

给定列表:

li = ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

如何找到包含字符串 amp 的(第一个)索引?请注意,amp 包含单词 example

仅供引用,这有效:li.index("example")

但这不是:li.index("amp")

最佳答案

您可以将生成器表达式与 next 结合使用和 enumerate :

>>> next((i for i,x in enumerate(li) if 'amp' in x), None)
5

如果没有找到这样的项目,这将返回 None

关于python - 在 Python 中,如何找到给定列表的子项的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227341/

相关文章:

python - 使用python中的struct模块打包和解包可变长度数组/字符串

python - get 上的 Redis 通配符键

python - 如何跳过循环中的项目

python - 以位存储扑克牌的更有效方法?

Python for 循环返回 IndexError : list index out of range

python - 根据元组将值插入像素

python - 读取文本文件、操作字符串并以特定格式导出 csv

python - 增加列表列表的 Pythonic 方式

c# - 通过接口(interface)枚举 - 性能损失

java - 如何通过 Intents 传递 List<CustomObject>