2013-05-01 237 views
1

我需要創建一個函數,它接收元組列表,然後輸出每個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)]) 

回答

4
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 
4

對於列表:

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) 
+0

這應該是公認的答案。肯定+1。 – TerryA 2013-05-01 06:42:33

+0

它更加優雅,但慢了大約1.5倍。 – Alexey 2013-05-01 06:53:20

相關問題