python - 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 语句与 2 个打印语句之间的逗号一起使用。
第三个 if 语句也适用于所有用分号分隔的语句。
逗号和分号组合的第二个 if 语句不再起作用。
第 4 个 if 语句,打印语句用逗号分隔,普通语句用分号隔开。
所以在我看来,虽然打印语句可以用逗号分隔,但普通语句不能。因此,最好在单行 if 语句中用分号分隔所有内容。
有人可以解释/确认这背后的逻辑吗?
解决方案
当你这样做时a, b
,function(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')
第二个更容易阅读并且不那么混乱。仅仅因为它适合一行并不能使它变得更好。
推荐阅读
- asp.net - 事件查看器中的 ASP.NET 2.0 System.AccessViolationException
- javascript - 如何不使用 array.forEach(_ => count++) 计算 array.push(undefined)?
- java - graphql 和 Spring Boot 上下文的问题
- python - 嵌套的 For 循环很快停止(初学者)
- javascript - React Router 是否有 onLoad 函数
- scala - 如何在解析的json中获取整数而不是浮点数
- javascript - 如何制作小标题?
- java - ClassLoader.loadLibrary NullPointerException 运行测试
- node.js - 使用 redis 和 hapi 构建 API
- javascript - 响应式相对元素调整大小 + 响应式文本叠加