【发布时间】:2016-03-27 02:57:21
【问题描述】:
如果len(a) > 0,我想打印列表a 的内容,否则我想打印-1。这似乎很简单,但它引发了TypeError,指出a 是一个int,而不是一个序列,只有当a 是一个空列表时:
>>> a = [2]
>>> print(*a if len(a) > 0 else -1)
2 # as expected
>>> a = []
>>> print(*a)
>>> # It has no trouble evaluating *a when a is empty
... ### HERE IS THE ERROR:
...
>>> print(*a if len(a) > 0 else -1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: print() argument after * must be a sequence, not int
>>> ### But this works fine:
...
>>> if len(a) > 0:
... print(*a)
... else:
... print(-1)
...
-1
为什么会这样?
表达式
x if C else y首先评估条件,C而不是 比x。如果C为真,则评估x并返回其值; 否则,y被评估并返回其值。
所以 *a 根本不应该被评估,但它会导致 TypeError?
我正在使用 Python 3.5
【问题讨论】:
标签: list python-3.x ternary-operator