如何根据引用列表中的项目对齐列表

时间:2017-06-18 13:00:49

标签: python

我想根据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)]

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

尝试输出:[('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)]

问题是每次新搜索都从listB中的第一项开始。

1 个答案:

答案 0 :(得分: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)]