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

use*_*925 2 python tuples list

我有一个元组列表,如果元组包含一个变量,我想找到该元组的索引。这是迄今为止我所拥有的简单代码:

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

但是我收到错误:

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

我做错了什么?

don*_*mus 5

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

indices = [i for i, tupl in enumerate(items) if tupl[0] == s]
Run Code Online (Sandbox Code Playgroud)


Pet*_*ood 2

看来您想要该值,因此您需要索引。

您可以使用以下命令在列表中搜索下一个匹配值next

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

>>> next(number for (name, number) in items
...      if name == 'show_scllo1')
'100'
Run Code Online (Sandbox Code Playgroud)

所以你根本不需要索引。