Python在元组列表中查找元组的索引

2024-06-06 12:40:13 发布

您现在位置:Python中文网/ 问答频道 /正文

所有人

我有以下问题。我有一个元组列表,如果元组包含变量,我想查找元组的索引。以下是我目前掌握的一个简单代码:

items = [('show_scllo1', '100'), ('show_scllo2', '200')]
s = 'show_scllo1'
indx = items.index([tupl for tupl in items if tupl[0] == s])
print(indx)

但是我得到了错误:

indx = items.index([tupl for tupl in items if tupl[0] == s])
ValueError: list.index(x): x not in list

我看了几篇类似的文章,但它们没有帮助我解决问题。你知道我做错了什么吗?


Tags: 代码in列表forindexifshowitems
3条回答

您正在检查items中是否存在不包含listlist。相反,您应该为找到感兴趣项的每个索引创建一个list

indx = [items.index(tupl) for tupl in items if tupl[0] == s]

下面将返回第一项为s的元组的索引

indices = [i for i, tupl in enumerate(items) if tupl[0] == s]

似乎你想要这个值,所以你要的是索引。

可以使用^{}在列表中搜索下一个匹配值:

>>> items = [('show_scllo1', '100'), ('show_scllo2', '200')]

>>> next(number for (name, number) in items
...      if name == 'show_scllo1')
'100'

所以你根本不需要索引。

相关问题 更多 >