简体   繁体   English

如何通过第二个键将列表搜索到嵌套列表中并将其附加到另一个列表中?

[英]How to search lists into a nested list by their second key and append it to another list?

Here is given a nested list: 这是一个嵌套列表:

nl=[['Tina', 37.2], ['Harry', 37.21], ['Berry', 37.21], ['Harsh', 39], ['Akriti', 41]]

Now I have to search for the lists which second value is 37.21. 现在,我必须搜索第二个值为37.21的列表。 Those lists which second value get matched with 37.21, will be appended into another list. 第二个值与37.21匹配的那些列表将被追加到另一个列表中。

So the output should be: 因此输出应为:

['Harry', 37.21], ['Berry', 37.21]

How do I do it? 我该怎么做?

You iterate over the whole list nl and extract the value at the second index of the nested lists and compare it with the desired value , if it matches then you simply append the nested list to another list answer 您遍历整个列表nl并提取嵌套列表的第二个索引处的值,并将其与所需值进行比较,如果匹配,则只需将嵌套列表追加到另一个列表answer

nl=[['Tina', 37.2], ['Harry', 37.21], ['Berry', 37.21], ['Harsh', 39], ['Akriti', 41]]        

answer = []

for sample_list in nl:
    if sample_list[1]==37.21:
        answer.append(sample_list)
print answer
>>> [['Harry', 37.21], ['Berry', 37.21]]

You can use list comprehension: 您可以使用列表理解:

 [l for l in nl if l[1] == 37.21]

which returns 哪个返回

[['Harry', 37.21], ['Berry', 37.21]]

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

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