在 Ruby 中我可以做类似的事情:
irb(main):001:0> x = []
=> []
irb(main):003:0> puts "hi ho" if x.count > 0 and x[0]
=> nil
Ruby 首先将 x.count >0
计算为 false,并且不再计算 x[0]
。
在 Python 中,我可以拥有一个包含以下内容的文件:
x = []
if x.count > 0 and x[0]:
print "hi ho"
当我运行时:
[onknows:/tmp] $ python test-if.py
Traceback (most recent call last):
File "test-if.py", line 2, in <module>
if x.count > 0 and x[0]:
IndexError: list index out of range
[onknows:/tmp] 1
因此,Python 也会评估 x[0]
,尽管没有理由评估它。有没有一种方法可以在Python中只使用一个if而不诉诸嵌套的if?我不想做这样的事情:
if x.count > 0:
if x[0]:
print "hi ho"
最佳答案
看起来您需要len
。
x = []
if len(x) > 0 and x[0]:
print("hi ho")
关于python - 如何在 Python 中执行此 Ruby if-with-and 并且不会使列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58407464/