Skip to content
Advertisement

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.

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement