Python 测试平均计算器返回错误 'list' 对象没有属性 'len'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21030116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python test Average Calculator returen error 'list' object has no attribute 'len'
提问by Abdullahi Farah
Hey this is a demo to show some of my classmates an intro to python and coding. The code below should be able to take a list like [0,1]and if run using the averagefunction would return 0.5. When run using a list the function below returns the error 'list' object has no attribute 'len'. How would I get this function to work without removing the len()function
嘿,这是一个演示,向我的一些同学展示 Python 和编码的介绍。下面的代码应该能够接受一个列表[0,1],如果使用该average函数运行将返回 0.5。当使用列表运行时,下面的函数返回错误'list' object has no attribute 'len'。我如何在不删除该len()功能的情况下使该功能正常工作
def average(lst):
total = 0
for item in lst:
total += item
averageGrade= total / lst.len()
return averageGrade
How would I also get it to return a float rather than an integer
我怎样才能让它返回一个浮点数而不是一个整数
采纳答案by Abhijit
Change the line
换线
averageGrade= total / lst.len()
to
到
averageGrade= total / len(lst)
Refer the python docs for the built-in len. The built-in len calculates the number of items in a sequence. As list is a sequence, the built-in can work on it.
有关内置len ,请参阅 python 文档。内置的 len 计算序列中的项目数。由于 list 是一个序列,因此内置函数可以处理它。
The reason it fails with the error 'list' object has no attribute 'len', because, listdata type does not have any method named len. Refer the python docs for list
失败的原因是错误'list' object has no attribute 'len',因为list数据类型没有任何名为len. 请参阅 python 文档以获取列表
Another important aspect is you are doing an integer division. In Python 2.7 (which I assume from your comments), unlike Python 3, returns an integer if both operands are integer.
另一个重要方面是您正在进行整数除法。在 Python 2.7(我从您的评论中假设)中,与 Python 3 不同,如果两个操作数都是整数,则返回一个整数。
Change the line
换线
total = 0.0
to convert one of your operand of the divisor to float.
将除数的操作数之一转换为浮点数。
回答by Harvester Haidar
or by changing
或者通过改变
averageGrade= total / lst.len()
to:
到:
averageGrade= total / lst.__len__()

