Reputation: 409
So, I have lists like this
list1 = [1,2,3]
list2 = [[1,4],[2,10],[3,11],[5,15],[20,30]]
I want to extract the numbers if the first number of the list2 is in the list1, therefore the output will be like:
list3 = [1,2,3,4,10,11]
Anyone can help me with how to do that?
Upvotes: 0
Views: 72
Reputation: 73450
You can do the following using the transpositional zip(*...)
pattern, if the order derives from list2
:
from itertools import chain
>>> list(chain(*zip(*(p for p in list2 if p[0] in list1))))
[1, 2, 3, 4, 10, 11]
If the order of the elements is based on the order in list1
:
>>> d = dict(list2)
>>> list(chain(list1, map(d.get, list1)))
[1, 2, 3, 4, 10, 11]
Instead of using the cryptic chain(*iterable)
pattern, you can also use the more explicit chain.from_iterable(iterable)
.
Upvotes: 3