我很难弄清楚如何从一个列表中找到最小值。比如说:
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)
返回元组中的最小值和最大值:
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)
0
处,最大值在索引length
处(或者相反)。一旦排序完成,就不需要使用min()
或max()
函数来查找这些值。 - Baldrickk只有老师会让你做这样的傻事。你可以提供一个预期的答案,或者一个独特的解决方案,而班上其他人将会是(呵欠)相同的...
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)
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)
somelist = [1,12,2,53,23,6,17]
,首先使用Pandas将其转换为数据框DataFrame。
然后你可以在数据框上使用describe()
方法。import pandas as pd
somelist = [1,12,2,53,23,6,17]
somelist_df = pd.DataFrame(somelist)
somelist_df.describe()
输出:
count 7.000000
mean 16.285714
std 18.052833
min 1.000000
25% 4.000000
50% 12.000000
75% 20.000000
max 53.000000
from __future__ import division
实际上导入了Python 3的除法运算符,覆盖了Python 2的运算符功能。 - monkut