为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

泛舟湖上清波郎朗 2021-12-17 14:46:27
我可以定义一个列表,这样:c = some_condition # True or Falsel = [    1, 2,   # always    3 if c else 4]# l = [ 1, 2, 3 ] if c is True, [ 1, 2, 4 ] otherwise但是我如何定义一个列表,[1,2,3]如果 c 为真,[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 dol = (    [        1, 2,    ]    +    ([3] if c1 else [])  # parentheses are mandatory    )# Of course, I know I couldl = [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);
查看完整描述

3 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

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


查看完整回答
反对 回复 2021-12-17
?
慕仙森

TA贡献1827条经验 获得超8个赞

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


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数组并使用掩码。


查看完整回答
反对 回复 2021-12-17
?
繁花如伊

TA贡献2012条经验 获得超12个赞

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


查看完整回答
反对 回复 2021-12-17
  • 3 回答
  • 0 关注
  • 326 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号