eikonal
eikonal

Reputation: 171

search elements of list in another list

This may have been already answered but believe me I may be so dumb (I have serious doubts right now) I couldn't even see the solution. To make my issue very simple, let's say I have two lists as follow: list_1

[2, 3, 4]

list_2

[['2', '54', '65', '22'],['2', '67', '66', '32'], ['10', '11', '43', '90'], ['3', '28', '81', '78'], ['4', '87', '19', '13'], ['4', '30', '51', '92'], ['4', '11', '44', '55'], ['13', '22', '69', '99']]

What I'm trying to do is to find if there is any match of any single element of list_1 with any first element of list_2, and if so return the line that will be later written out (but I should be able to do this). Practically, in this scenario the result I'm after is:

2 54 65 22
2 67 66 32
3 28 81 78
4 87 19 13
4 30 51 92
4 11 44 55

I ended up with so many for, if loops and list comprehensions that I lost my count and I acknowledge I'm not much familiar with python rules. Hope I can get any help from here.

Upvotes: 1

Views: 61

Answers (2)

Marcus Müller
Marcus Müller

Reputation: 36482

You could just filter your list2:

result = filter(lambda vector: int(vector[0]) in list1, list2)

notice that you must convert the strings contained in the lists in list2 (notice the '!) to integers first, that's what int() does here.

Upvotes: 0

Eugene Soldatov
Eugene Soldatov

Reputation: 10145

Use list comprehension, just check that first element of each list in b exists in a:

a = [2, 3, 4]
b = [['2', '54', '65', '22'],['2', '67', '66', '32'], ['10', '11', '43', '90'], ['3', '28', '81', '78'], ['4', '87', '19', '13'], ['4', '30', '51', '92'], ['4', '11', '44', '55'], ['13', '22', '69', '99']]

c = [x for x in b if int(x[0]) in a]

Upvotes: 1

Related Questions