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:
JavaScript
x
10
10
1
#python 2.7.5
2
list1 = ['aa', 'ab', 'bb', 'bc', 'cc']
3
list2 = [['aa', 1, 3, 7],['de', 2, 2, 1],['bc', 3, 4, 4]]
4
5
list3 = []
6
for x in list1:
7
for y in list2:
8
if x == y:
9
list3.append(y)
10
So I would want list3 to contain [['aa',1,3,7],['bc', 3, 4, 4]]
but instead I just get the whole of list2.
Advertisement
Answer
Try a more simple approach that is closer to what you want:
JavaScript
1
4
1
for e in list2:
2
if e[0] in list1:
3
list3.append(e)
4
You need e[0]
since list2
is a list of lists. You can also write this in a single line using the filter() function:
JavaScript
1
2
1
list3 = filter(lambda e: e[0] in list1, list2)
2
or using list comprehension:
JavaScript
1
2
1
list3 = [e for e in list2 if e[0] in list1]
2