如何根据另一个列表的顺序对列表重新排序?

时间:2019-02-15 17:57:56

标签: python arrays sorting dictionary reorderlist

我有一个列表,按照特定的顺序,例如['hello', 'I', 'like', 'sunshine'],第二个列表包含所有第一个列表和一些额外的元素['You', 'like', 'pie', 'sunshine', 'and', 'rainbows', 'hello', 'I']。这是一个荒谬的示例,但是基本上主要的思想是第一个列表是第二个列表的子集,但是来自第一个列表的元素的显示顺序与原始出现的顺序不同(它们在第二个列表中被加乱清单)。我想对第二个列表进行重新排序,以使其具有按原始顺序从第一个列表的开头开始的元素,然后具有其唯一元素。因此,此重新排序的第二个列表将是['hello', 'I', 'like', 'sunshine', 'You', 'pie', 'and', 'rainbows']

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

2 个答案:

答案 0 :(得分:1)

您可以获取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']

答案 1 :(得分: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']
相关问题