Python在列表中查找元组中的最大值,平均值,最小值和加起来的值
问题描述:
我需要创建一个函数,它接收元组列表,然后输出每个tupple中的总最高值,最低值,平均值和总计值。Python在列表中查找元组中的最大值,平均值,最小值和加起来的值
例如: 这是怎样才能在:
([(99,86,70,7),(100, 96, 65, 10), (50, 40, 29, 11)])
我需要一个函数,它的最高INT的每个元组,但只能在指数[0]。然后它需要在索引[1]处将这些数字进行平均,然后在索引[2]处找到最低的int,然后将每个tupple的最后一个索引中的值加起来。
所以输出应该是这样的:
(100, 74, 29, 28)
这是我现在有。它的完全错误和愚蠢的,我发现元组非常混乱。我试图这样做只使用while
/for
循环,但我只是与元组和列表混淆。
def grades(listt):
count=0
while count < len(listt):
x=();
for i in range(0, len(listt)):
x(listt(0[count])) > x(listt(i[count]))
print x[count]
print grades([(99,86,70,7),(100, 96, 65, 10), (50, 40, 29, 11)])
答
def grades(alist):
highest, average, lowest, sumvalues = alist[0]
for i in alist[1:]:
if i[0] > highest: highest = i[0]
average += i[1]
if i[2] < lowest: lowest = i[2]
sumvalues += i[3]
average = average/len(alist)
return highest, average, lowest, sumvalues
答
对于列表:
grades = [(99,86,70,7),(100, 96, 65, 10), (50, 40, 29, 11)]
你会做:
toFindHighest, toFindAverage, toFindLowest, toFindSum = zip(*grades)
highest = max(toFindHighest)
average = sum(toFindAverage)/float(len(toFindAverage))
lowest = min(toFindLowest)
total = sum(toFindSum)
这应该是公认的答案。肯定+1。 – TerryA 2013-05-01 06:42:33
它更加优雅,但慢了大约1.5倍。 – Alexey 2013-05-01 06:53:20