python - 如何在 Python 中执行此 Ruby if-with-and 并且不会使列表索引超出范围

标签 python ruby

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

相关文章:

python - 如何在 Anaconda Python(Windows 平台)中安装 xgboost?

ruby - 您可以使用Ruby中的Net::HTTP发出YouTube分析API请求吗?

ruby HTTPClient : How to use persistent connections?

ruby-on-rails - 有没有办法在 Active Record 中到达那里

javascript - 使用 Ruby Grape 服务器发送的事件

java - Pig 将制表符 (\t) 作为动态 CSV 解析的参数

python - scrapy链接提取器在链接末尾添加等号

java - 动态实例化一个类似于Java的Ruby类

python - GAE Python - 操作错误 : (2013, 'Lost connection to MySQL server during query')

Python,与 joblib : Delayed with multiple arguments 并行化