文章内容

2021/4/23 18:13:37,作 者: 黄兵

Python 求列表中位数、最大值、最小值、平均值方法

有一个列表,在Python中需要求最大值、最小值、中位数、平均数,以下是具体代码:

平均值:

# Python program to get average of a list
# Using reduce() and lambda 
  
# importing reduce()
from functools import reduce
  
def Average(lst):
    return reduce(lambda a, b: a + b, lst) / len(lst)
  
# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
  
# Printing average of the list
print("Average of the list =", round(average, 2))

# Output
Average of the list = 35.75

最小值和最大值:

Python可以使用max()和min()来获取数列最大值和最小值:

# Python code to demonstrate the working of
# max()
 
# printing the maximum of 4,12,43.3,19,100
print("Maximum of 4,12,43.3,19 and 100 is : ",end="")
print (max( 4,12,43.3,19,100 ) )

# Output
Maximum of 4,12,43.3,19 and 100 is : 100


# Python code to demonstrate the working of
# min()
 
# printing the minimum of 4,12,43.3,19,100
print("Minimum of 4,12,43.3,19 and 100 is : ",end="")
print (min( 4,12,43.3,19,100 ) )

# Output
Minimum of 4,12,43.3,19 and 100 is : 4

中位数:

Python3.4有statistics.median函数:

返回数值数据的中位数(中间值)。

当数据点数为奇数时,返回中间数据点。当数据点的数量为偶数时,通过取两个中间值的平均值来对中位数进行插值:

import statistics

items = [6, 1, 8, 2, 3]

statistics.median(items)
#>>> 3



参考资料:

1、Find average of a list in python

2、max() and min() in Python

3、Finding median of list in Python

分享到:

发表评论

评论列表