简体   繁体   中英

Get value for a match from a list of tuples

I have a list with tuples. I am trying to find value for a match in tuple. For example, if M is in a , then it should return 10 . Can someone help me figuring out what I am missing here?

>>> c
'M'
>>> a
[[('N', '64')], [('W', '1024')], [('M', '10')], [('C', '2')], [('RA', '8')]]

>>> c in a
False

>>> a[2][0][0]
'M'

>>> [item for item in a if a[item][0][0] == c]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not list

you can convert your list to a dictionary

d = dict(map(lambda x: x[0], a))   

and use simple lookup:

>>> d['M']
10

That last bit should be:

[item for item in a if item[0][0] == c]

This is because item already refers to the highest-level list in a , so you do not need the a[item] .

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