Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据参考列表中的项目对齐列表_Python - Fatal编程技术网

Python 如何根据参考列表中的项目对齐列表

Python 如何根据参考列表中的项目对齐列表,python,Python,我想根据listA中的项目对齐listB 列表a=[('how',0),('to',1),('align',2),('a',3),('list',4),('substand',5),('to',6),('a',7),('reference',8),('list',9)] 列表B=[('preduce',0),('to',1),('a',2),('reference',3),('list',4),('how',5),('to',6),('align',7),('a',8),('list',9)]

我想根据listA中的项目对齐listB

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

列表B=
[('preduce',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代表列表B中的y,如果x[0]==y[0]]代表列表A中的x],])

尝试的输出:
[('how',5),('to',1),('to',6),('align',7),('a',2),('a',8),('list',4),('list',9),('substand',0),('to',1),('to',6),('a',2),('a',8),('reference',3),('list',4),('list',9)]


问题是每个新搜索都从列表B中的第一项开始。

您的两个序列包含(键、值)对。您需要根据序列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)]

不清楚你想做什么。@LaurentPorte,谢谢。我希望列表B中的项目与列表A中的项目以相同的方式排列,就像您在所需输出中看到的一样。@Laurent_LAPORTE,感谢您的解决方案,它可以工作。