简体   繁体   中英

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?

Easy task for comprehension + zip:

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM