2016-08-25 17 views
2

我從xlsx文件讀取。 我試圖按路由器列分組並添加所有mb coulmn。但是,我有一些重複,我不知道爲什麼?爲什麼在使用python的畝代碼中有重複

這是代碼,可以幫到我嗎?

def totalroutermb(): 
    arrayItems = items 
    arrayItems2 = items 
    arrayRouterAndMb = [] 
    num_mb = float(0.0) 

    for user in arrayItems: 
     for user2 in arrayItems2: 
      if user.router == user2.router: 
       num_mb += float(user2.download_in_mb) 
       arrayItems2.remove(user2) 
     dict = {"router": user.router, "Total": num_mb} 
     arrayRouterAndMb.append(dict) 

    for user in arrayRouterAndMb: 
     print(user) 
    print("\n") 

和打印這樣的:

{'router': 'Kut_2007_CO_Sag_a7:41', 'Total': 8861222409750.0} 
{'router': 'Kut_2017_CO_Sol_e0:06', 'Total': 12448391550377.031} 
{'router': 'Kut_Giris_AsansorSol_a7:3e', 'Total': 12460052878502.203} 
{'router': 'Kut_Giris_AsansorSol_a7:3e', 'Total': 12460052878502.203} 
{'router': 'Kut_Giris_AsansorSol_a7:3e', 'Total': 12470382956627.203} 
{'router': 'Kut_Giris_Masa1_a4:82', 'Total': 18009186394127.203} 
{'router': 'Kut_Kat1_Sag1_a9:3e', 'Total': 35296935066002.2} 
{'router': 'Kut_Kat1_Sag1_a9:3e', 'Total': 35316851362878.78} 
+2

爲什麼arrayItems和arrayItems2兩個副本的相同項目,但然後進行比較?爲什麼你要循環兩個相同的迭代? –

+1

如果我要運行這個代碼,會有'NameError',因爲'items'沒有被定義。請提供[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve) –

回答

0

我解決它!對不起,但我只用python的幾天,我正在學習

def totalroutermb(): 
    arrayRouterAndMb = [] 

    for item in items: 
     aux = [item.router.strip(), float(item.download_in_mb)] 
     arrayRouterAndMb.append(aux) 
    # order array 
    arrayRouterAndMb.sort() 

    # add all mb from each router 
    arrayEachRouterMb = [] 
    pos = 0 
    firstObj = arrayRouterAndMb[0] 
    num_mb = firstObj[1] 
    for obj in arrayRouterAndMb: 
     pos += 1 
     if pos == len(items): 
     dict = {"Total": num_mb, "router": obj[0]} 
     arrayEachRouterMb.append(dict) 
     break 
     objNext = arrayRouterAndMb[pos] 
     if objNext[0] == obj[0]: 
     num_mb += float(objNext[1]) 
     elif obj[0] != objNext[0]: 
     dict = {"Total": num_mb, "router": obj[0]} 
     arrayEachRouterMb.append(dict) 
     num_mb = objNext[1] 

    for user in arrayEachRouterMb: 
     print(user) 
    print("\n") 
相關問題