0
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.

Georgy
  • 9,972
  • 7
  • 57
  • 66
d123
  • 1,397
  • 2
  • 11
  • 21
  • Related: [Select value from list of tuples where condition](https://stackoverflow.com/questions/7876272/select-value-from-list-of-tuples-where-condition) – Georgy Jun 29 '20 at 20:50

4 Answers4

1
>>> 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}
poke
  • 339,995
  • 66
  • 523
  • 574
0
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]
Ajay
  • 4,831
  • 2
  • 21
  • 28
0

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']]
fferri
  • 16,928
  • 4
  • 40
  • 82
0
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)
Lautern
  • 57
  • 1
  • 8