我很难弄清楚如何从列表中找到min 例如
somelist = [1,12,2,53,23,6,17]
如何通过定义(def
)函数
我不想使用内置函数min
答案 0 :(得分:33)
from __future__ import division
somelist = [1,12,2,53,23,6,17]
max_value = max(somelist)
min_value = min(somelist)
avg_value = 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)
答案 1 :(得分:3)
返回元组中的最小值和最大值:
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)
答案 2 :(得分:1)
只有一位老师会要求您做这样的愚蠢的事情。 您可以提供预期的答案。或一个独特的解决方案,而课程的其余部分将(打哈欠)相同...
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)
解决方案很简单。用它来使自己远离明显的选择。
答案 3 :(得分:0)
list=[]
n = int(input("Enter the length of your list: "))
for i in range (1,n+1):
a=int(input("Enter the %d number: " %i ))
list.append(a)
min=list[0]
max=list[0]
for i in range(1,n):
if max<list[i]:
max=list[i]
if min>list[i]:
min=list[i]
print(" %d is the biggest number " %max)
print(" %d is the smallest number " %min)