首页 > 解决方案 > Python列表定义-根据条件插入或不插入元素

问题描述

我可以定义一个列表:

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
);

标签: pythonlistconditional

解决方案


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

推荐阅读