我可以定义一个列表,这样: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
慕仙森
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数组并使用掩码。
添加回答
举报
0/150
提交
取消
