繁体   English   中英

Python:为什么返回时出现list out of index错误但打印时不出现

[英]Python : Why list out of index error appears if returning but not when printing

嗨,当我在 pythonprinciples.com 上解决挑战时,我遇到了一个错误。

挑战内容:

定义一个名为 all_equal 的 function,它接受一个列表并检查列表中的所有元素是否相同。

例如,调用 all_equal([1, 1, 1]) 应该返回 True。

引发错误的解决方案:

def all_equal(nestedList):
   return len(nestedList) == nestedList.count(nestedList[0])

print(all_equal([1, 1, 1]))

错误:

Traceback (most recent call last):
  File "/tmp/pyrunnerSDobDKmo/code.py", line 7, in 
    result = all_equal([])
  File "/tmp/pyrunnerSDobDKmo/usercode.py", line 2, in all_equal
    return (len(nestedList) == nestedList.count(nestedList[0]))
IndexError: list index out of range

当我在自己的电脑(不是在线解释器)上尝试此解决方案时,或者如果打印而不是返回,则不会引发错误。 那么这个错误 python 版本是否依赖或可能有其他原因?

如果列表不为空,您的 function 可以工作。 就像是

def all_equal(nestedList):
   return len(nestedList) == 0 or len(nestedList) == nestedList.count(nestedList[0])

应该管用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM