gpt4 book ai didi

python - 按另外两个列表对 Python 中的列表进行排序

转载 作者:太空狗 更新时间:2023-10-29 17:43:29 26 4
gpt4 key购买 nike

我的问题与这两个链接非常相​​似12 :

我有三个不同的列表。我想根据 List2(升序)对 List1 进行排序。但是,我在 List2 中有重复。然后我想按 List3(降序)对这些重复进行排序。够困惑吗?

我有什么:

List1 = ['a', 'b', 'c', 'd', 'e']
List2 = [4, 2, 3, 2, 4]
List3 = [0.1, 0.8, 0.3, 0.6, 0.4]

我想要的:

new_List1 = ['b', 'd', 'c', 'e', 'a']

'b' 出现在 'd' 之前,因为 0.8 > 0.6。 'e' 在 'a' 之前出现,因为 0.4 > 0.1。

最佳答案

我认为您应该能够通过以下方式做到这一点:

paired_sorted = sorted(zip(List2,List3,List1),key = lambda x: (x[0],-x[1]))
l2,l3,l1 = zip(*paired_sorted)

在行动中:

>>> List1 = ['a', 'b', 'c', 'd', 'e']
>>> List2 = [4, 2, 3, 2, 4]
>>> List3 = [0.1, 0.8, 0.3, 0.6, 0.4]
>>> paired_sorted = sorted(zip(List2,List3,List1),key = lambda x: (x[0],-x[1]))
>>> l2,l3,l1 = zip(*paired_sorted)
>>> print l1
('b', 'd', 'c', 'e', 'a')

这是它的工作原理。首先,我们使用 zip 从您的列表中匹配相应的元素。然后,我们首先根据 List2 中的项目对这些元素进行排序,然后(否定)List3 中的项目对这些元素进行排序。然后我们只需要使用 zip 和参数解包再次提取 List1 元素——尽管如果您想确保在日期而不是元组。

如果您不能轻易否定 List3 中的值,这会变得有点困难——例如如果它们是字符串。您需要分 2 次进行排序:

paired = zip(List2,List3,List1)
rev_sorted = sorted(paired,reverse=True,key=lambda x: x[1]) #"minor" sort first
paired_sorted = sorted(rev_sorted,key=lambda x:x[0]) #"major" sort last
l2,l3,l1 = zip(*paired_sorted)

(如果您愿意,可以使用 operator.itemgetter(1) 代替上面的 lambda x:x[1])。这是有效的,因为 python 排序是“稳定的”。它不会重新排序“相等”的元素。

关于python - 按另外两个列表对 Python 中的列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13957624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com