简体   繁体   English

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

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

I have a list of tuples and I want to find the index of a tuple if the tuple contains a variable.我有一个元组列表,如果元组包含一个变量,我想找到该元组的索引。 Here is a simple code of what I have so far:这是我到目前为止的简单代码:

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

However I am getting the error:但是我收到错误:

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

What I am doing wrong?我做错了什么?

The following will return you the indices of the tuples whose first item is s以下将返回第一项为s的元组的索引

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

It seems as though you want the value, so you're asking for the index.好像您想要这个值,所以您要的是索引。

You can search the list for the next matching value, using next :您可以使用next在列表中搜索下一个匹配值:

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

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

So you don't really need the index at all.所以你根本不需要索引。

You are checking for the presence of a list in items , which doesn't contain a list .您正在检查items中是否存在不包含listlist Instead, you should create a list of each index where the item of interest is found:相反,您应该为找到感兴趣项目的每个索引创建一个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)

Is how you should probably do that你应该怎么做

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

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