Python 列表定义 - 根据条件插入或不插入元素

Python list definition - inserting elements or not depending on a condition

我可以这样定义一个列表:

c = some_condition # True or False
l = [
    1, 2,   # always
    3 if c else 4
]
# l = [ 1, 2, 3 ] if c is True, [ 1, 2, 4 ] otherwise

但是 如果 c 为真,我如何定义一个列表 [1,2,3],否则 [1,2]

l = [
    1, 2,
    3 if c    # syntax error
]

l = [
    1, 2,
    3 if c else None    # makes [1,2,None]
]

l = [
    1, 2,
    3 if c else []    # makes [1,2,[]]
]

# This is the best that I could do
l = (
    [
        1, 2,
    ]
    +
    ([3] if c1 else [])  # parentheses are mandatory
    )

# Of course, I know I could
l = [1, 2]
if c:
    l.append(3)

此外,我想知道如何在条件为真时插入多个元素:例如 3, 4 而不是 3

例如,在 Perl 中,我可以这样做:

@l = (
    1, 2,
    $c1 ? 3 : (),        # empty list that shall be flattened in outer list
    $c2 ? (4,5) : (6,7), # multiple elements
);

[x for x in range(1,5) if x<3 or c]

最接近的是使用单独定义的生成器函数:

def maker(condition):
    yield 1
    yield 2
    if condition:
        yield 3
        yield 4

print(list(maker(True)))
print(list(maker(False)))

输出:

[1, 2, 3, 4]
[1, 2]

也就是说,Python 并不是真正用于此类操作,因此它们会很笨重。通常更习惯于基于谓词过滤列表,或者创建一个相同形状的布尔 numpy 数组并使用掩码。

c = some_condition # True or False

l = [1, 2] + [x for x in [3] if c]
print(l)

输出>>>

[1, 2, 3] # when c = True
[1, 2]    # when c = False

您可以根据需要扩展它

l = [1, 2] + [x for x in [3] if c] + [x for x in [4] if not c]

输出>>>

[1, 2, 3] # when c = True
[1, 2, 4]    # when c = False