2015-11-03 44 views
1

嵌套列表進行遍歷如何將列表的索引與浮點數進行比較?

cost =[[125900], [115000], 
[105900], 
[85000], 
[150000], 
[155249], 
[97500]] 

初始化變量

index = 0 
cost_len = len(cost) 
below_avg = 0 
above_avg = 0 
total = 0 

for循環來計算成本

for i in cost: 
    total = total + sum(i) 
    print(total) 

成本計算的平均總所有元素的

avg = total/len(cost) 

嘗試計算索引是否高於或低於平均

for i in cost: 
    while index <= cost_len: 
     if i > avg: 
      above_avg+=1 
     elif i < avg: 
      below_avg +=1 
     index+=1 

當試圖評價成本的索引,則返回「類型錯誤:unorderable類型:列表()>浮動()」。我如何比較列表的指數和變量avg?

+0

在上一個代碼位中,什麼是'index','cost_len','above_avg','below_avg'?它們從未被顯示爲被初始化。 –

+0

不用擔心。我收回了我的近距離投票。 –

回答

0

沒有必要,如果你想比較各子表的多個元素拼合列表:

total = sum(sum(x) for x in cost) 
cost_len = sum(len(x) for x in cost) 
avg = total/cost_len 
above = sum([sum([y > avg for y in x for x in cost])]) 
below = sum([sum([y < avg for y in x for x in cost])]) 
exact = cost_len - (above + below) 

有關此解決方案几點:

  1. totalcost_len計算使用生成器而不是從結果中創建列表。這樣可以節省一些內存和可能的執行時間,因爲中間結果不需要額外的存儲空間。
  2. abovebelow是嵌套的生成器,基本上等同於您嘗試執行的嵌套循環。

這是一個什麼樣的最終嵌套循環原理,以及如何解決它的解釋:

for i in cost: 
    while index <= cost_len: 
     if i > avg: 
      above_avg+=1 
     elif i < avg: 
      below_avg +=1 
     index+=1 

i遍歷的cost的元素,但內while循環阻止它以後做任何事情處理第一個值i。請注意,內部循環中i的值不會改變,因此比較將在第一個i中反覆完成,而其他index將在cost_len + 1之前完成比較。爲了保護您的雙環結構,你可以做如下:

for i in cost: 
    for j in i: 
     if j > avg: 
      above_avg+=1 
     elif j < avg: 
      below_avg +=1 

在這一點上,你並不真正需要index

1

假設每個子列表中的一個元素,扁平化似乎是最好的:

flat_cost = [x[0] for x in cost] 
total = sum(flat_cost) 
avg = total /len(cost) 
above = len([x for x in flat_cost if x > avg]) 
below = len([x for x in flat_cost if x < avg]) 
+0

對於每個列表中的任意數量的元素,您可以將[j替換爲j中的i,代表i中的i] – BlivetWidget

+0

謝謝,非常乾淨,正是我所期待的。 –

0

如果你將要處理的號碼清單或數字數組,那麼我會建議你使用NumPy的(http://docs.scipy.org/doc/numpy/user/index.html )這個任務:

import numpy as np 

cost = np.array([[125900], 
[115000], 
[105900], 
[85000], 
[150000], 
[155249], 
[97500]]) 

cost-np.average(cost) 

>>>array([[ 6678.71428571], 
     [ -4221.28571429], 
     [-13321.28571429], 
     [-34221.28571429], 
     [ 30778.71428571], 
     [ 36027.71428571], 
     [-21721.28571429]]) 

cost - np.average(cost)是使用NumPy的廣播功能的一種方式。您可以從數組中減去一個值(np.average(cost))(cost),它會對整個數組進行減法運算,從而爲您提供答案數組。

+0

這不是我正在尋找的,但我會嘗試用Numpy來解決它以熟悉模塊,謝謝。 –