Comparing two list and getting a new list in python

Tags: python list
By : Sahil
Source: Stackoverflow.com
Question!

I have a list - a and a list of columns - b.

a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1]
b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]

I want to take the columns from list "b" which when compared with list "a" have the value 1.

I want the output to be:

c = ["C", "D", "F", "G", "J"]

How can I do it?

By : Sahil


Answers

A classic approach:

>>> c = [b[i] for i in range(len(b)) if i<len(a) and a[i] == 1]
>>> c
['C', 'D', 'F', 'G', 'J']


Done in many ways:

List Comprehension

a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1]
b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
print [b[index] for index, item in enumerate(a) if item == 1]

Filter with Lambda

a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1]
b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
print filter(lambda index, item: len(a) > index and a[index]==1, enumerate(b))

Note that the list comprehension will be faster because it goes only up to the length of a rather than the list b, in case b is bigger.



I'd do it with zip and list comprehension.

>>> a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1]
>>> b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
>>> c = [x[0] for x in zip(b, a) if x[1] == 1]
>>> c
['C', 'D', 'F', 'G', 'J']
>>>


This video can help you solving your question :)
By: admin