首页 > 解决方案 > 在 Python 中使用一个行列表推导从一个列表中获取两个列表

问题描述

我有一个包含 True 和 False 值的列表。使用列表推导,从这个列表中,我可以得到两个单独的列表,其中一个只有 True 值,另一个只有 False 值,如下所示:

aList  = [True, False, False, True, False, True, True]
trues  = [ x for x in aList if x==True ]
falses = [ x for x in aList if x==False ]

print(trues)  # [True, True, True, True]
print(falses) # [False, False, False]

是否可以在一行中使用列表理解从一个列表中获取两个单独的列表?就像是:

trues, falses = [ [a,b] for x in aList a=True if x else b=False]

在这里,我收到错误:“SyntaxError:无效语法”在 a=True 的“True”下方提到插入符号

标签: pythonlistlist-comprehension

解决方案


它或多或少与您所拥有的相同,但压缩在一行中:

aList  = [True, False, False, True, False, True, True]
trues,falses  = [x for x in aList if x], [x for x in aList if not x]

这样,您将获得两个列表。如果你把它括在括号中,你会得到一个列表。


推荐阅读