查找列表的最小值、最大值和平均值 [英] Find min, max, and average of a list

查看:79
本文介绍了查找列表的最小值、最大值和平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚如何从列表中找到 min例如

I am having hard time to figure out how to find min from a list for example

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

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

how can I find min and max of this list with defining (def) a function

我不想使用内置函数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)

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

If you want to manually find the minimum as a function:

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 和其他统计数据:

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

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

这篇关于查找列表的最小值、最大值和平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆