简体   繁体   中英

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

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 :

>>> 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 . Instead, you should create a list of each index where the item of interest is found:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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