如何在Python中使用Ruby if-with-和如何使列表索引不超出范围

问题描述 投票:1回答:4

在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评估为假,并且不费心去评估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并且不求助于nested if?我不想做类似的事情:

if x.count > 0:
  if x[0]:
     print "hi ho" 
python ruby
4个回答
0
投票

看起来您需要len

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

0
投票

Python supports short-circuiting on and,因此如果第一个参数为and,则不评估第二个参数。

False始终为真:

x.count > 0

您应该将其替换为In [12]: [].count > 0 Out[12]: True ,并且可以正常工作:

len(x)

0
投票

[Python使用if len(x) > 0 and x[0]: # ... and时会对布尔表达式进行惰性求值。

来自文档:

表达式x和y首先计算x;如果x为假,则返回其值;否则,将评估y并返回结果值。

表达式x或y首先计算x;如果x为true,则返回其值;否则,将评估y并返回结果值。

Python列表方法count()返回obj在列表中出现的次数。

您应该使用or来获取列表的长度。

len(x)

0
投票

因此Python也评估x [0],尽管没有理由对其进行评估。

我认为这对您有用,是最基本的形式:

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

这将评估X的长度,并且(如果大于0,则为True。

但是,如果变量“ x”不存在,则会出错。评估“ x”是否存在,并且至少包含一项,是(我认为)您正在尝试通过...完成的工作]

if len(x) > 0: 
    print("Hi Ho!")
如果变量

exists且包含任何值,Python将求值为if x[0]: print("Hi Ho!") 。如果变量exists,但不包含值,它将计算为True。如果变量不存在,Python将出错。

所以,这可能就是您想要的...

False
© www.soinside.com 2019 - 2024. All rights reserved.