我知道您可以在python中执行以下操作:
>>> conditional = False >>> x = [1 if conditional else 2, 3, 4] [ 2, 3, 4 ]
但是我会怎么做呢?
>>> conditional = False >>> x = [1 if conditional, 3, 4] [ 3, 4 ]
也就是说,我不想用1另一个数字代替。如果conditional错误,我想简单地忽略它。
1
conditional
使用串联:
x = ([1] if conditional else []) + [3, 4]
换句话说,生成一个其中包含可选元素或为空的子列表。
演示:
>>> conditional = False >>> ([1] if conditional else []) + [3, 4] [3, 4] >>> conditional = True >>> ([1] if conditional else []) + [3, 4] [1, 3, 4]
当然,这个概念也适用于更多元素:
x = ([1, 2, 3] if conditional else []) + [4, 5, 6]