Python oneliner if条件,包含多个用逗号和分号分隔的语句


a = True
if a : print('msg1'), print('msg2');
# msg1 and msg2 are printed
if a : print('msg1'), print('msg2'), b = 1;
# if a : print('msg1'), print('msg2'), b = 1;
#       ^
# SyntaxError: can't assign to function call
if a : print('msg1'); print('msg2'); b = 1;
# msg1 and msg2 are printed and b is also assigned the value 1
if a : b = 1; c = 5; print(b), print(c)
# b and c are assigned values 1 and 5, and both are printed

第一个if语句使用两个print语句之间的逗号
第三个if语句适用于所有用分号分隔的语句。

逗号和分号组合的第二个if语句已不起作用
第4个if语句的打印语句用逗号分隔,而正常语句用分号分隔。

所以在我看来,虽然打印语句可以用逗号分隔,但普通语句不能。因此,最好在oneliner-if语句中用分号分隔所有内容。

有人能解释/证实这背后的逻辑吗?

当执行a, bfunction(value), function(value)时,这与function(value); function(value)非常不同。逗号有效地创建了一个元组,而分号分隔语句。这就是为什么赋值在分号示例中有效,而在逗号示例中无效的原因:

# this is the form of the comma statement
print('a'), b = 1
# raises a syntax error
# this is what the semicolon statements look like
print('a')
b = 1

真正的解决办法是:不要试图把所有东西都写成一句话。比较两种说法:

if a: b = 1; print('msg1'), print('msg2')
if a:
b = 1
print('msg1')
print('msg2')

第二种更容易阅读,也不那么杂乱。仅仅因为它符合一条线并不能让它变得更好。

最新更新