【发布时间】:2020-11-03 10:15:02
【问题描述】:
>>> count = 0
>>> for c in "##.#.":
... count = count + 1 if c == '.' else 0
...
>>> print(count)
1
>>> count = 0
>>> for c in "##.#.":
... count = count + (1 if c == '.' else 0)
...
>>> print(count)
2
为什么第一个例子没有打印出 2 的计数器?
【问题讨论】:
-
如果第二个是你的意图,那么为什么不使用
count += 1 if c == '.' else 0呢?
标签: python operator-precedence conditional-operator