[英]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
. 例如,如果
M
在a
,则它应返回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]
. 这是因为
item
已经指的是最高级别的列表a
,所以你不需要a[item]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.