2015-11-09 91 views
2

我對從文本文件中排序數據有一半的問題。我想從3個加權數字中找出平均值,並打印出特定平均值所屬文本文件中的哪個名稱。Python,排序平均值

我設法做到了這一點的最高平均水平,但我有幾個問題找到最低的平均水平。

來自文件的示例文本。

Shoes 210 130 67 
Bags 167 321 459 

文本文件中的位置0是部門的名稱。文件中的位置1是「好評」。位置2'公平投票'。位置3'差投票'。

列表中最高盤是鞋,平均而言爲2.351,排名中最低的是袋子,平均數爲1.692。

我已經定義了一個函數來計算平均值,並調用它沒有任何問題的最高平均水平。

highestAverage = 0 
    highestAvgDepName = 0  
    if choice2 == 1: 
     calculateAverage(allDepartments,choice2) 
     for x in range (10): 
      if highestAverage < calculateAverage(allDepartments, x): 
       highestAverage = calculateAverage(allDepartments, x) 
       highestAvgDepName = x 

我唯一的問題是得到這個找到最低的平均值。我已經嘗試創建一個計算平均值的新函數,並將其乘以-1,將所有數字都轉爲負數,技術上這應該是最大的-1.692,但它會拋出55. ***。

我已經看着泡沫排序,但是,我不明白如何從文本文件做到這一點。

def calculateAverage(allDepartments, choice2): 
total = allDepartments[choice2][1] + allDepartments[choice2][2] + allDepartments[choice2][3] 
return((allDepartments[choice2][1]*3 + allDepartments[choice2][2]*2 + allDepartments[choice2][3])/total) 

回答

1

您可以使用此:

highestAverage = 0 
highestAvgDepName = 0  
if choice2 == 1: 
    calculateAverage(allDepartments,choice2) 
    for x in range (10): 
     if highestAverage > calculateAverage(allDepartments, x): 
      highestAverage = calculateAverage(allDepartments, x) 
      highestAvgDepName = x 
+0

我嘗試了顛倒操作符,但它給了我一個錯誤的部門,平均值爲0.000 –

+1

您可以發佈calculateAverage的代碼嗎? –

+1

@ s.kelly你可以將它發佈在你的問題的可讀性? – SirParselot

0

你可以在你的部門存放在鍵入平均一本字典,然後儲存您的平均值在列表和排序列表,以獲得最高和最低平均像所以

def calculateAverage(choice2): 
    total = choice2[0] + choice2[1] + choice2[2] 
    return((choice2[0]*3 + choice2[1]*2 + choice2[2])/total) 

d={} 
l = [] 
with open(file,'r') as f: 
    for i in f: 
     tmp = i.split() 
     avg = calculateAverage([float(j) for j in tmp[1:]]) 
     d[avg] = tmp[0] 
     l.append(avg) 
    l = sorted(l) 
print 'Highest: {} {:.4}'.format(d[highest], highest) 
print 'Lowest: {} {:.4}'.format(d[lowest], lowest) 

Highest: Shoes 2.351 
Lowest: Bags 1.692 

,或者你能做到這樣,它使用較少的內存

def calculateAverage(choice2): 
    total = choice2[0] + choice2[1] + choice2[2] 
    return((choice2[0]*3 + choice2[1]*2 + choice2[2])/total) 
d={} 
l = [] 
highest = -100000 
lowest = 100000 

with open(file,'r') as f: 
    for i in f: 
     tmp = i.split() 
     avg = calculateAverage([float(j) for j in tmp[1:]]) 
     d[avg] = tmp[0] 
     if avg > highest: 
      highest = avg 
     if avg < lowest: 
      lowest = avg 
print 'Highest: {} {:.4}'.format(d[highest], highest) 
print 'Lowest: {} {:.4}'.format(d[lowest], lowest) 
+0

謝謝!我還沒有學過這樣的詞典,但它很有用。在打印報表時,是否有辦法將最高和最低更改爲3sf? (即2.351) –

+0

@ s.kelly是的,您可以使用格式來打印帶有約束的字符串。這裏是[鏈接](https://pyformat.info/),所以你可以閱讀更多。打印複雜的字符串時非常有用。 – SirParselot