我可以定义一个列表,以便:
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
);
答案 0 :(得分:1)
使用单独定义的生成器函数可以找到最接近的结果:
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
数组并使用遮罩,这是比较习惯的做法。
答案 1 :(得分:1)
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
答案 2 :(得分:0)
[x for x in range(1,5) if x<3 or c]