0

I have a list that contains many lists with a fixed number of elements:

info = [['N', 100, 'A'], ['O', 99, 'A'], ['C', 105, 'A'], ...]

I want to find the index of the element that contains 'N' and 100, namely 0. I tried something like this to get the element itself:

matches = [a for name in a[2] and resnum in a[5] for a in info]

which didn't work. Is there a way to do this with list comprehensions?

Tonechas
  • 12,665
  • 15
  • 42
  • 74
sodiumnitrate
  • 2,773
  • 5
  • 27
  • 45

2 Answers2

2

You can use next() and enumerate():

>>> next(i for i, (a, b, _) in enumerate(info) if a == 'N' and b == 100)
0
>>> next(i for i, (a, b, _) in enumerate(info) if a == 'C' and b == 105)
2

Note that next() would throw a StopIteration exception if there is no match - you can either handle it with try/except or provide a default value, say, -1:

>>> next((i for i, (a, b, _) in enumerate(info) if a == 'invalid' and b == 0), -1)
-1

_ is a canonical way to name the throwaway variables (we don't need the third values of the sublists in this particular case).

Community
  • 1
  • 1
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148
2

If you want to fix your list comprehension, this should do:

>>> [info.index(x) for x in info if x[0]=='N' and x[1]==100]
[0]
Iron Fist
  • 10,237
  • 2
  • 17
  • 32