'Find matching values in a list of lists
I'm trying to iterate over a list of lists in python 2.7.5 and return those where the first value is found in a second list, something like this:
#python 2.7.5
list1 = ['aa', 'ab', 'bb', 'bc', 'cc']
list2 = [['aa', 1, 3, 7],['de', 2, 2, 1],['bc', 3, 4, 4]]
list3 = []
for x in list1:
for y in list2:
if x == y:
list3.append(y)
So I would want list3 to contain [['aa',1,3,7],['bc', 3, 4, 4]] but instead I just get the whole of list2.
Solution 1:[1]
Try a more simple approach that is closer to what you want:
for e in list2:
if e[0] in list1:
list3.append(e)
You need e[0] since list2 is a list of lists. You can also write this in a single line using the filter() function:
list3 = filter(lambda e: e[0] in list1, list2)
or using list comprehension:
list3 = [e for e in list2 if e[0] in list1]
Solution 2:[2]
There's just a bug in your code. You need x == y[0] instead of x == y. The latter is comparing a string to a list.
You can also use list comprehensions
>>> [x for x in list2 if x[0] in list1]
[['aa', 1, 3, 7],['bc', 3, 4, 4]]
Solution 3:[3]
It looks like your issue is because you are attempting to compare a list of elements against a list of a list of elements.
If you step through the for loop, you'll see that on your first iteration you are comparing
'aa' against ['aa', 1, 3, 7], which is probably not what you would like to do.
If you're just comparing the first element, you will need to change your for loop to:
for x in list1:
for y in list2:
if x == y[0]:
list3.append(y)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aaron Digulla |
| Solution 2 | |
| Solution 3 |
