更新时间:2023-08-25 18:09:40
使用串联:
x = ([1] if conditional else []) + [3, 4]
换句话说,生成一个其中包含可选元素或为空的子列表.
In other words, generate a sublist that either has the optional element in it, or is empty.
演示:
>>> conditional = False
>>> ([1] if conditional else []) + [3, 4]
[3, 4]
>>> conditional = True
>>> ([1] if conditional else []) + [3, 4]
[1, 3, 4]
这个概念当然也适用于更多元素:
This concept works for more elements too, of course:
x = ([1, 2, 3] if conditional else []) + [4, 5, 6]