我正在尝试合并两个按降序排序的用户输入列表。我了解如何合并两个列表然后进行排序,但是我在相反的情况下苦苦挣扎。
# user list input
a = [int(x) for x in input("List 1: ").split()]
b = [int(y) for y in input("List 2: ").split()]
a.sort(reverse=True)
b.sort(reverse=True)
print(a + b)
比如我想输入:[1, 3, 3, 6]
& [1, 4, 5]
,我的输出是:[6, 5, 4, 3, 3, 1, 1]
答案 0 :(得分:0)
我建议使用 sorted()
。
# user list input
a = [int(x) for x in input("List 1: ").split()]
b = [int(y) for y in input("List 2: ").split()]
print(sorted(a+b,reverse=True))
输入/输出
List 1: 1 2 3
List 2: 1 2 3
[3, 3, 2, 2, 1, 1]
答案 1 :(得分:0)
您可以为此使用 heapq.merge
。它需要多个排序的迭代并将它们合并为一个排序的输出,因此:
c = list(heapq.merge(
sorted(a, reverse=True),
sorted(b, reverse=True),
reverse=True)
请注意,这也适用于可迭代对象(例如延迟计算的潜在可消耗对象),这是您更有可能使用它的时候(组合已排序的可迭代对象时)。
我假设您对列表进行了预先排序,或者您只是想知道如何执行此操作,因为最好先合并列表然后对它们进行排序(使用 sorted
或对它们进行变异)与.sort()
)。