简体   繁体   中英

Retrieve lists from a list of lists based on the given first elements

list1 = [1, 3, 5, 7]
list2 = [[1, "name1", "sys1"], [2, "name2", "sys2"], [3, "name3", "sys3"], [4, "name4", "sys4"]]

I've got the following 2 lists, I would like to be able to retrieve from list2 every item that matched in list1.

so, the result would be like:

result = [[1, "name1", "sys1"], [3, "name3", "sys3"]]

Separately is there also an easy way to find out the items that did not match,

notmatch = [5, 7]

I have read this Find intersection of two lists? but it does not produce the result I need.

>>> ids = set(list1)
>>> result = [x for x in list2 if x[0] in ids]
>>> result
[[1, 'name1', 'sys1'], [3, 'name3', 'sys3']]

>>> ids - set(x[0] for x in result)
{5, 7}
In [3]: result=[i for i in list2 if i[0] in list1]
Out[4]: [[1, 'name1', 'sys1'], [3, 'name3', 'sys3']]

In [5]: nums=[elem[0] for elem in result]
In [6]: [i for i in list1 if i not in nums]
Out[6]: [5, 7]

Use a set for looking up indices: it will have faster lookup time:

>>> indices = set(list1)

Matching items:

>>> matching = [x for x in list2 if x[0] in indices]
>>> matching
[[1, 'name1', 'sys1'], [3, 'name3', 'sys3']]

non-matching items:

>>> nonmatching = [x for x in list2 if x[0] not in indices]
>>> nonmatching
[[2, 'name2', 'sys2'], [4, 'name4', 'sys4']]
list1 = [1, 3, 5, 7]
list2 = [[1, "name1", "sys1"], [2, "name2", "sys2"], [3, "name3", "sys3"], [4, "name4", "sys4"]]
result = []

for elem in list1:
    for x in range(len(list2)):
        if elem == list2[x][0]:
            result.append(list2[x])
print(result)

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