How to calculate the average using the average function in Python?

In Python, you can use the built-in functions sum() and len() to calculate the total sum and number of elements in a list, and then divide them to get the average.

Here is an example code using the average() function to calculate the mean.

def average(lst):
    return sum(lst) / len(lst)

# 测试
numbers = [1, 2, 3, 4, 5]
avg = average(numbers)
print("平均值为:", avg)

Output the results:

平均值为: 3.0

In the above example, the average() function takes a list as a parameter, calculates the total sum of the list using the sum() function, then calculates the length of the list using the len() function. Finally, the total sum is divided by the length to get the average value, which is then returned as the function’s output.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds