【问题标题】:How to reorder list based off of another list's ordering?如何根据另一个列表的排序重新排序列表?
【发布时间】:2019-07-09 21:58:10
【问题描述】:

我有一个按特定顺序排列的列表,比如['hello', 'I', 'like', 'sunshine'],我还有第二个列表,其中包含第一个列表的所有内容和一些额外的元素['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']。这是一个荒谬的例子,但主要思想是第一个列表是第二个列表的子集,但是第一个列表中的元素出现的顺序与它们最初出现的顺序不同(它们在第二个中被打乱列表)。我想对第二个列表重新排序,以便它以原始顺序从第一个列表开始,然后具有其唯一元素。因此,这个重新排序的第二个列表就像['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows']

希望这是有道理的。我实际上并不关心唯一元素如何出现在最终重新排序的列表中(它们可以重新排列,但我关心的是第一个列表中的元素出现在开头并保持原始顺序)。我如何实现这一目标?我有点迷茫。

【问题讨论】:

  • 请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 On topichow to ask... the perfect question 在此处申请。 StackOverflow 不是设计、编码、研究或教程资源。但是,如果您遵循您在网上找到的任何资源,进行诚实的编码尝试并遇到问题,那么您将有一个很好的示例可以发布。

标签: python arrays sorting dictionary reorderlist


【解决方案1】:

这是一个不错的单行解决方案:

a = ['hello', 'I', 'like', 'sunshine']
b = ['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']

b = sorted(b, key=lambda x: a.index(x) if x in a else len(a) + b.index(x))
# b = ['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows']

【讨论】:

    【解决方案2】:

    您可以使用 List1,并将 List2 中不在 List1 中的每个项目附加到 List1 中。

    l1 = ['hello', 'I', 'like', 'sunshine']
    l2 = ['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']
    
    new_list = l1.copy()
    
    for item in l2:
        if item not in l1:
            new_list.append(item)
    
    print(new_list)
    

    输出:

    ['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows']
    

    【讨论】:

    • 这是修改第一个列表,根据 OP 的问题,这可能不是有意的。他/她明确表示他/她想要变异 第二个列表。
    猜你喜欢
    • 2021-05-21
    • 2015-02-27
    • 2022-11-17
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2022-12-22
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多