简体   繁体   English

嵌套循环中的python list comprehension

[英]python list comprehension in nested loops

One basic question in list comprehension as i am starting on that, 列表理解中的一个基本问题是我开始这样做,

can a list comprehension return two arrays? 列表理解可以返回两个数组吗?

like I was trying to convert my code to list comprehension 就像我试图将我的代码转换为列表理解

b=[10,2,3]
c=[10,11,12]
d=[]
f=[]
a=10
for i in b:
    if a>i:
        for j in c:
            d.append(j)

print d

I am able to convert the above code using list comprehension as 我可以使用list comprehension将上面的代码转换为

print [j  for i in b if a>i  for j in c ]

But now I want to add an extra else block to my initial code and looks like 但现在我想在我的初始代码中添加一个额外的块,看起来像

b=[10,2,3]
c=[10,11,12]
d=[]
f=[]
a=10
for i in b:
        if a>i:
            for j in c:
                d.append(j)
        else:
          f.append(i)
print d
print f

d=[10, 11, 12, 10, 11, 12]
f=[10]

is there any way I can add this extra else to my initial list comprehension? 有什么方法可以将这个额外的东西添加到我的初始列表理解中吗?

You can't use a list comprehension for your second example, because you are not building a single list . 您不能在第二个示例中使用列表推导,因为您没有构建单个列表 List comprehensions build one list object, not two. 列表推导构建一个列表对象,而不是两个。

You could use two separate list comprehensions: 您可以使用两个单独的列表推导:

d = [j for i in b if a > i for j in c]
f = [i for i in b if a <= i]

or you could simplify your loops a little by using list.extend() or += augmented assignments: 或者你可以通过使用list.extend()+=增强的赋值来简化你的循环:

for i in b:
    if a > i:
        d.extend(c)
    else:
        f.append(i)

or 要么

for i in b:
    if a > i:
        d += c
    else:
        f.append(i)

To answer your question : 回答你的问题:

Can a list comprehension return two arrays? 列表解析可以返回两个数组吗?

Yes, it can: 是的,它可以:

>>> [[1] * n for n in [3, 5]]
[[1, 1, 1], [1, 1, 1, 1, 1]]
>>> d, f = [[1] * n for n in [3, 5]]
>>> d
[1, 1, 1]
>>> f
[1, 1, 1, 1, 1]

Just for fun, here's a one-liner to define both d and f : 只是为了好玩,这里有一个单行来定义df

d, f = [[j for i in b if f(i) for j in g(i)] for (f, g) in [(lambda x: x < a, lambda x: c), (lambda x: x >= a, lambda x: [x])]]

It's obviously a bad idea, though, and @MartijnPieters's answer is preferable. 不过,这显然是一个坏主意,@ MartijnPieters的答案更可取。

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

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