在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"
我假设这会对你有用,最基本的形式是:
这将计算X的长度,如果大于0,则响应True。你知道吗
但是,如果变量“x”不存在,它将出错。评估“x”是否存在,并且至少包含一个项目,是(我假设)你试图用它来完成的。。。你知道吗
如果变量存在并且包含任何值,Python将计算为
True
。如果变量存在,但不包含值,它将计算为False
。如果变量不存在,Python将出错。你知道吗所以,这可能就是你要找的。。。你知道吗
编辑:
注意,如果
x
作为列表存在,但不包含任何值,len(x)
将计算为0
。但是,如果您尝试计算x[0]
,您仍然会得到一个错误,但这是一个IndexError
,而不是“变量不存在”错误。你知道吗Pythonsupports short-circuiting on ^{} 因此,如果第一个参数是
False
,那么第二个参数就不会被计算。你知道吗x.count > 0
总是正确的:您应该用
len(x)
替换它,它可以正常工作:看来你需要
len
。你知道吗相关问题 更多 >
编程相关推荐