简体   繁体   English

在包含两个特定元素的列表中查找列表

[英]Find lists in a list that contains two specific elements

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 . 我想找到包含'N'100的元素的索引,即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? 有没有办法用列表推导做到这一点?

You can use next() and enumerate() : 您可以使用next()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()将抛出StopIteration异常-您可以使用try/except进行处理,也可以提供默认值 -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). _是命名一次性变量的规范方法(在这种情况下,我们不需要子列表的第三个值)。

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]

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

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