2017-06-18 74 views
0

我想根據listA中的項目對齊listB。如何根據參考列表中的項目對齊列表

= listA的[('how', 0), ('to', 1), ('align', 2), ('a', 3), ('list', 4), ('according', 5), ('to', 6), ('a', 7), ('reference', 8), ('list', 9)]

數組listB = [('according', 0), ('to', 1), ('a', 2), ('reference', 3), ('list', 4), ('how', 5), ('to', 6), ('align', 7), ('a', 8), ('list', 9)]

希望的輸出:

[('how', 5), ('to', 1), ('align', 7), ('a', 2), ('list', 4), ('according', 0), ('to', 6), ('a', 8), ('reference', 3), ('list', 9)] 

嘗試:[('how', 5), ('to', 1), ('to', 6), ('align', 7), ('a', 2), ('a', 8), ('list', 4), ('list', 9), ('according', 0), ('to', 1), ('to', 6), ('a', 2), ('a', 8), ('reference', 3), ('list', 4), ('list', 9)]

的:sum([[y for y in listB if x[0]==y[0]] for x in listA],[])

從試圖輸出問題是每個新的搜索都從listB中的第一個項目開始。

+0

尚不清楚你想要做什麼。 –

+0

@LaurentLAPORTE,謝謝。我希望listb中的項目以與lista中的項目相同的方式排列,就像您在所需輸出中看到的一樣。 – Boby

回答

1

您的兩個序列包含(鍵,值)對。並且您想根據序列listA重新排序(稱爲「對齊」)第二序列listB

注意:由於密鑰列表包含重複項,因此不能(很容易)使用list.sort函數重新排序第二個序列。你需要編寫你自己的特定功能。

這裏是我會做到這一點:

def align(seq, ref_seq): 
    '''align the sequence *seq* according to the keys in the reference sequence *ref_seq*''' 
    seq = list(seq) # local copy 
    keys = [item[0] for item in seq] 
    result = [] 
    for item_ref in ref_seq: 
     key_ref = item_ref[0] 
     if key_ref in keys: 
      index = keys.index(key_ref) 
      keys.pop(index) 
      result.append(seq.pop(index)) 
    # keep what's left 
    result.extend(seq) 
    return result 

您可以使用它像這樣:

import pprint 
pprint.pprint(align(listB, listA)) 

你得到:

[('how', 5), 
('to', 1), 
('align', 7), 
('a', 2), 
('list', 4), 
('according', 0), 
('to', 6), 
('a', 8), 
('reference', 3), 
('list', 9)] 
+0

@Laurent_LAPORTE,感謝您的解決方案,它的工作原理。 – Boby