2015-02-04 299 views
0

我對Python和編程一般都很陌生。我在這個網站上發現了很多有用的東西,但是我也很困惑自己是否想要完成我所需要的最好的方法。Python比較嵌套列表

簡而言之,我有2個csv文件,RemoteLA和Master。每個訂單項都包含訂單號,姓氏,名字,MI,賬號#。我必須從RemoteLA中找到不在主文件中的項目。我主要關心的是匹配/驗證Order#first,然後是Account#,然後是名稱。有些情況下,我可以有兩個相同的訂單#但不同的名稱和賬戶號碼,只要它在主文件中列出相同即可。最後,如果RemoteLA訂單號碼位於主文件中,但賬號被錯誤列出,我希望將它打印在不同於主訂單號碼根本不在主文件中的輸出中。以下是我的簡化列表。

RemoteLA = [['100', 'JACKSON', 'CHRIS', 'D', '12344'], ['110', 'SMITH', 'JANET', 'L' '1223'], ['120', 'STONE', 'MAX', 'W', '1233']] 
Master = [['100', 'JACKSON', 'CHRIS', 'D', '1234'], ['90', 'BARST', 'JOEY', 'D', '1344'], ['80', 'NORDON', 'BEV', 'A', '1122'], ['120', 'STONE', 'MAX', 'W', '1233']] 

就像我說的,我已經嘗試使用套,元組等的列表很多事情我最後的「嘗試」是使用while循環如下,我只是想看看我是否能得到的結果我想,但看來我仍然在做錯事。

i=0 
while i < len(RemoteLA): 
    j = 0 
    while j < len(Master): 
     if RemoteLA[i][0] == Master[j][0]: 
      if RemoteLA[i][1] == Master[j][1]: 
       if RemoteLA[i][2] == Master[j][2]: 
        print('All match') 
       elif RemoteLA[i][2] == '9999': 
        pass 
       else: 
        print('Account number does not match') 
      else: 
       print('Name does not match') 
     else: 
      print('Order number does not match') 
     j = j + 1 
    i = i + 1 

任何幫助或推動正確的方向將非常感激。對不起,我很抱歉。謝謝。

+0

你的3個ifs可以用'all(a == b代替a,b in zip(RemoteLA [i] [,Master [j]))''雖然9999的東西在Python中是奇怪的 – njzk2

+0

你不需要做這樣討厭的索引變量。在RemoteLA **中更好地使用**,無需擁有這樣的C風格索引變量 – tschm

+0

我實際上有4個「遠程」文件進行比較,其中一個帳號與所有9個一起列出 - 直到這是固定的,任何帳戶號碼列爲9999我想通過沒有做任何事情。 – ceitel

回答

0

一個短得多(雖然只是效率低下)將是:

import itertools 
for master,remote in itertools.product(Master, RemoteLA): 
    if all(r == m for r,m in zip(master, remote)): 
     print "Match", master 

更高效的版本將是列表第一排序(O(nlogn)),爲了有一個O(N)比較。

+0

這是我的不好。我的清單全部按訂單#排序,但我上面的檢測清單是按順序手動輸入的。 – ceitel

1

如果我明白,帳號是唯一的。因此將它們用作字典鍵。在這裏,讓我們重新組織你的數據:

def orderSummary(lst): 
    info = collections.defaultdict(dict) 
    for item in lst: 
    acct = item[4] 
    orderinfo = info[acct] 
    ordernum = item[0] 
    if ordernum in orderinfo: 
     print "duplicate order number" 
    else: 
     orderinfo[ordernum] = tuple(item[1:4]) #the name 
    return info 

remote = orderSummary(RemoteLA) 
master = orderSummary(Master) 

現在我們準備檢查遠程對主:

def checkRemoteAgainstMater(remote,master): 
    for acct,info in remote.items(): 
    masterinfo = master.get(acct,None) 
    if masterinfo is None: 
     print "bad account number {}".format(acct) 
    else: 
     for order in info: 
     if order not in masterinfo: 
      print "Master missing order" 
     elif info[order] != masterinfo[order]: 
      print "name mismatch" 

checkRemoteAgainstMater(remote,master) 

心連心。

+0

謝謝你的建議。這聽起來像是我最好的選擇。我會稍微處理一下, – ceitel