在 python 3.5 中的 for 循环中使用三元运算符时出现奇怪的行为
weird behavior while using ternary operator in for loop in python 3.5
我在python3测试三元运算符的时候遇到了这个奇怪的现象
import string
test = ""
testing = chr(0) if chr(0) in test else ""
for c in string.ascii_letters + testing:
print(c)
每行打印 a~Z 1 个字符,但是
import string
test = ""
for c in string.ascii_letters + chr(0) if chr(0) in test else "":
print(c)
不会打印任何内容。
有人可以给我解释一下吗?
更改为:
for c in string.ascii_letters + (chr(0) if chr(0) in test else ""):
它会起作用。
为什么? Operator precedence。您当前的代码实际上是:
for c in (string.ascii_letters + chr(0)) if chr(0) in test else "":
这是由于运算符优先级:+
比 if
绑定更紧密。
在第一个片段中,testing
计算为“”,因为 chr(0)
不在 test
中。所以,循环结束 ascii_letters + "",即只是字母。
在第二个中,+
首先被评估; if
因此将整个事情评估为 ""
并且循环就在空字符串上。
我在python3测试三元运算符的时候遇到了这个奇怪的现象
import string
test = ""
testing = chr(0) if chr(0) in test else ""
for c in string.ascii_letters + testing:
print(c)
每行打印 a~Z 1 个字符,但是
import string
test = ""
for c in string.ascii_letters + chr(0) if chr(0) in test else "":
print(c)
不会打印任何内容。
有人可以给我解释一下吗?
更改为:
for c in string.ascii_letters + (chr(0) if chr(0) in test else ""):
它会起作用。
为什么? Operator precedence。您当前的代码实际上是:
for c in (string.ascii_letters + chr(0)) if chr(0) in test else "":
这是由于运算符优先级:+
比 if
绑定更紧密。
在第一个片段中,testing
计算为“”,因为 chr(0)
不在 test
中。所以,循环结束 ascii_letters + "",即只是字母。
在第二个中,+
首先被评估; if
因此将整个事情评估为 ""
并且循环就在空字符串上。