简体   繁体   English

比较两个列表并在python中获取新列表

[英]Comparing two list and getting a new list in python

I have a list - a and a list of columns - b. 我有一个列表-a和一个列列表-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. 我想从列表“ b”中获取与列表“ a”相比具有值1的列。

I want the output to be: 我希望输出为:

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

How can I do it? 我该怎么做?

Easy task for comprehension + zip: 理解+ 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. 我会用zip和list理解来做到这一点。

>>> 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 用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. 请注意,列表推导会更快,因为如果b更大,它只会到达a的长度而不是列表b的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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