简体   繁体   English

在两个单独的列表上使用相同的列表推导

[英]Using identical list comprehensions on two separate lists

This feels like a simple question, but I haven't been able to figure it out and I haven't been able to find the answer anywhere. 这感觉就像一个简单的问题,但我无法弄清楚,我无法在任何地方找到答案。

In one line, how can I use two identical list comprehensions on two different lists, and return the results as two seperate lists? 在一行中,如何在两个不同的列表中使用两个相同的列表推导,并将结果作为两个单独的列表返回?

I am trying to do this: 我想这样做:

listx = [x for x in listx if x != None]
listy = [y for y in listy if y != None]

Is there a way to do this in one line? 有没有办法在一行中做到这一点? Perhaps using map() or a list comprehension? 也许使用map()或列表理解?

虽然我不明白为什么它必须是单行,但这应该做你想要的:

listx, listy = [[x for x in alist if x != None] for alist in [listx, listy]]

I think the original one and nested list comprehension is just fine and very readable. 我认为原始的和嵌套列表理解很好,非常易读。

However, if you want to think in terms of functions having an input and output: 但是,如果您想考虑具有输入和输出的函数:

You want to filter some contents from a list, so it can be written as: 您想要从列表中filter一些内容,因此可以将其写为:

listx = filter(None, listx)
listy = filter(None, listy)

There is a repeated pattern. 有一个重复的模式。 The pattern here is we are changing multiple lists at once. 这里的模式是我们一次更改多个列表。

map(function, collection)

So you can break down your original problem to map multiple lists using a filter . 因此,您可以使用filter分解原始问题以map多个lists

listx, listy = map(lambda x: filter(None, x), [listx, listy])

很简单:

listx, listy = [x for x in listx if x != None], [y for y in listy if y != None]

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

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