Can I optionally include one element in a list without an else statement in python?

前端 未结 4 646
闹比i
闹比i 2020-12-20 18:00

I know you can do something like this in python:

>>> conditional = False
>>> x = [1 if conditional else 2, 3, 4]
[ 2, 3, 4 ]
4条回答
  •  半阙折子戏
    2020-12-20 18:12

    If you truly want to avoid the else, you could write a generator for the list items:

    def gen_x(conditional):
        if conditional:
            yield 1
        for v in [3, 4]:
            yield v
    

    Or, since Python 3.3:

    def gen_x(conditional):
        if conditional:
            yield 1
        yield from [3, 4]
    

    And then:

    x = list(gen_x(conditional))
    

提交回复
热议问题