嵌套循环中的python list comprehension

sya*_*yam 3 python 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
Run Code Online (Sandbox Code Playgroud)

我可以使用list comprehension将上面的代码转换为

print [j  for i in b if a>i  for j in c ]
Run Code Online (Sandbox Code Playgroud)

但现在我想在我的初始代码中添加一个额外的块,看起来像

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]
Run Code Online (Sandbox Code Playgroud)

有什么方法可以将这个额外的东西添加到我的初始列表理解中吗?

Mar*_*ers 7

您不能在第二个示例中使用列表推导,因为您没有构建单个列表.列表推导构建一个列表对象,而不是两个.

您可以使用两个单独的列表推导:

d = [j for i in b if a > i for j in c]
f = [i for i in b if a <= i]
Run Code Online (Sandbox Code Playgroud)

或者你可以通过使用list.extend()+=增强的任务来简化你的循环:

for i in b:
    if a > i:
        d.extend(c)
    else:
        f.append(i)
Run Code Online (Sandbox Code Playgroud)

要么

for i in b:
    if a > i:
        d += c
    else:
        f.append(i)
Run Code Online (Sandbox Code Playgroud)