AttributeError: 'list' object has no attribute 'sum'
时间: 2023-09-27 20:09:08 浏览: 403
This error occurs when you try to use the method "sum" on a list object, but it does not exist. The "sum" method is only available for certain data types such as tuples, sets, and dictionaries.
To fix this error, you can either convert the list to a different data type that supports the "sum" method or write your own function to calculate the sum of the elements in the list.
Here's an example of how to use the built-in "sum" function on a list of integers:
```
my_list = [1, 2, 3, 4, 5]
total = sum(my_list)
print(total) # Output: 15
```
If you need to sum a list of elements that are not integers, you can use a for loop to iterate over the list and add up the values:
```
my_list = [1.5, 2.2, 3.7, 4.1, 5.9]
total = 0
for num in my_list:
total += num
print(total) # Output: 17.4
```
阅读全文