2017-06-18 71 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