如何在Python中实现这个Ruby ifwithand,而不使列表索引超出范围

2024-10-03 11:12:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在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" 

Tags: andpytestifmaincounthi事情
3条回答

So Python evaluates x[0] as well although there is no reason to evaluate it.

我假设这会对你有用,最基本的形式是:

if len(x) > 0: 
    print("Hi Ho!")

这将计算X的长度,如果大于0,则响应True。你知道吗

但是,如果变量“x”不存在,它将出错。评估“x”是否存在,并且至少包含一个项目,是(我假设)你试图用它来完成的。。。你知道吗

if x[0]:
    print("Hi Ho!")

如果变量存在并且包含任何值,Python将计算为True。如果变量存在,但不包含值,它将计算为False。如果变量不存在,Python将出错。你知道吗

所以,这可能就是你要找的。。。你知道吗

try:
    if len(x) > 0:
        print("Hi Ho!")
    else:
        print("Variable does not seem to contain a value!")
except (NameError, AttributeError, ValueError): 
    print("Variable does not exist!")

编辑:

注意,如果x作为列表存在,但不包含任何值,len(x)将计算为0。但是,如果您尝试计算x[0],您仍然会得到一个错误,但这是一个IndexError,而不是“变量不存在”错误。你知道吗

Pythonsupports short-circuiting on ^{}因此,如果第一个参数是False,那么第二个参数就不会被计算。你知道吗

x.count > 0总是正确的:

In [12]: [].count > 0
Out[12]: True

您应该用len(x)替换它,它可以正常工作:

if len(x) > 0 and x[0]:
  # ...

看来你需要len。你知道吗

x = []
if len(x) > 0 and x[0]:
    print("hi ho")

相关问题 更多 >