我正在寻找某种“二元”(非三元)if,它允许在Python中定义列表成员资格,类似于它在列表推导中的工作方式。考虑下面的代码:
abc = (1, 0, 2)
my_list = [i for i in abc if i]
# observed: [1, 2]
a = 1
b = 0
c = 2
my_list = ["d" if a; "e" if b; "f" if c]
# expected: ["d", "f"]
Run Code Online (Sandbox Code Playgroud)
虽然第一个块有效,但第二个块却不起作用(毫不奇怪)。然而,我发现这个语法非常Pythonic。有没有什么东西可以接近它,例如
my_list = ["d" if a else Nothing; "e" if b else Nothing; "f" if c else Nothing]
Run Code Online (Sandbox Code Playgroud)
列表if推导式本身不是表达式,只是生成器表达式语法的一部分,它允许您提供单个布尔条件来过滤生成器生成的内容。
你的第二个块可以写成
my_list = [value
for (value, condition) in zip(["d", "e", "f"],
[a, b, c])
if condition]
Run Code Online (Sandbox Code Playgroud)
正如 user2357112 支持 Monica 所指出的,这是由模块compress提供的类型捕获的itertools:
from itertools import compress
my_list = list(compress(["d", "e", "f"],
[a, b, c]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |