Sahil
Sahil

Reputation: 439

Comparing two list and getting a new list in python

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?

Upvotes: 1

Views: 89

Answers (4)

Ganesh Matkam
Ganesh Matkam

Reputation: 368

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']

Upvotes: 3

thiruvenkadam
thiruvenkadam

Reputation: 4250

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.

Upvotes: 0

Pavel Gurkov
Pavel Gurkov

Reputation: 757

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']
>>>

Upvotes: 2

Netwave
Netwave

Reputation: 42708

Easy task for comprehension + zip:

>>> c = [y for (x, y) in zip(a, b) if x == 1]
>>> c
['C', 'D', 'F', 'G', 'J']

Upvotes: 8

Related Questions