gpt4 book ai didi

python - 查找列表的最小值、最大值和平均值

转载 作者:太空狗 更新时间:2023-10-29 18:13:37 25 4
gpt4 key购买 nike

我很难弄清楚如何从列表中找到最小值例如

somelist = [1,12,2,53,23,6,17]

如何通过定义 (def) 函数找到此列表的最小值和最大值

我不想使用内置函数min

最佳答案

from __future__ import division

somelist = [1,12,2,53,23,6,17]
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

如果您想手动找到最小值作为函数:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
min_value = None
for value in somelist:
if not min_value:
min_value = value
elif value < min_value:
min_value = value
return min_value

Python 3.4 引入了 statistics包,它提供 mean 和其他统计数据:

from statistics import mean, median

somelist = [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

关于python - 查找列表的最小值、最大值和平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27009247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com