Python 查找列表(数组)的最小值最大值和平均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27009247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:18:39  来源:igfitidea点击:

Python find min max and average of a list (array)

pythonarraysmaxmin

提问by mtkilic

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

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

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

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

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

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

I do not want to use built-in function min

我不想使用内置函数 min

采纳答案by monkut

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 introduced the statisticspackage, which provides meanand additional stats:

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)

回答by 2RMalinowski

Return min and max value in tuple:

返回元组中的最小值和最大值:

def side_values(num_list):
    results_list = sorted(num_list)
    return results_list[0], results_list[-1]


somelist = side_values([1,12,2,53,23,6,17])
print(somelist)

回答by peawormsworth

Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...

只有老师会叫你做这种傻事。您可以提供预期的答案。或者一个独特的解决方案,而班上的其他人将(打哈欠)一样......

from operator import lt, gt
def ultimate (l,op,c=1,u=0):
    try:
        if op(l[c],l[u]): 
            u = c
        c += 1
        return ultimate(l,op,c,u)
    except IndexError:
        return l[u]
def minimum (l):
    return ultimate(l,lt)
def maximum (l):
    return ultimate(l,gt)

The solution is simple. Use this to set yourself apart from obvious choices.

解决方法很简单。使用它使自己与明显的选择区分开来。