繁体   English   中英

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

[英]Find index of a tuple in a list of tuples

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

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

我做错了什么?

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

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

好像您想要这个值,所以您要的是索引。

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

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

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

所以你根本不需要索引。

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

indx = [items.index(tupl) for tupl in items if tupl[0] == s]
index = next((i for i,v in enumerate(my_tuple_of_tuple) if v[0] == s),-1)

你应该怎么做

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM