python - 在 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”下方提到插入符号
解决方案
它或多或少与您所拥有的相同,但压缩在一行中:
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]
这样,您将获得两个列表。如果你把它括在括号中,你会得到一个列表。
推荐阅读
- java - 来自 Postman 的 Post 请求中的状态 403 无效的 CSRF 令牌
- node.js - 为 Node.js 模块中重新导出的 JS 函数生成 TypeScript 声明
- android - Android (Kotlin) 中的 lateinit 问题 - java.lang.RuntimeException
- android - 无法解析 Android Studio 中的符号“注释”?
- angular - 显示相同的时间计数,但同时显示两个组件
- c++ - 使用 sfml 在矩形的向量中查找鼠标点击
- javascript - 如何调用同名的父函数?
- swift - 模态控制器在关闭时仍然是最顶层的视图控制器
- c# - 从所有 XML 值中修剪空格
- r - ggplot:将两个变量绘制成一个方面