gpt4 book ai didi

python - 比较两个列表以找到更大的列表

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

我有两个列表,需要按最大元素比较它们,如果是并列,则比较它们的第二大元素,如果是并列,则按第三大元素迭代整个数组。

例如:

list1= [0,2,3,6,12]
list2= [1,2,3,6,12]
list3= [1,4,5,8,12]
list4= [1,4,5,9,12]

所以 list4 > list3 > list2 > list1。

我写了一个函数来完成这个:

def compare(x,y):
if sorted(x)==sorted(y):
return "Tie"
for index in range(len(x)-1,-1,-1):
if sorted(x)[index]>sorted(y)[index]:
return x
elif sorted(x)[index]<sorted(y)[index]:
return y

我想知道是否有更简洁、更有效的方法来编写该函数,因为它看起来不太像 Pythonic。

编辑:使用“<”和“>”比较列表会将列表从最小索引排序到最大索引,而不是从最大索引到最小索引。反转将使“>”和“<”成为最简单的解决方案。

最佳答案

这个怎么样?

>>> list1= [0,2,3,6,12]
>>> list2= [1,2,3,6,12]
>>> list3= [1,4,5,8,12]
>>> list4= [1,4,5,9,12]
>>> def sort_lists_by_maxes(*lists):
return sorted(lists, key=lambda x: sorted(x, reverse=True), reverse=True)

>>> sort_lists_by_maxes(list1, list2, list3, list4)
[[1, 4, 5, 9, 12], [1, 4, 5, 8, 12], [1, 2, 3, 6, 12], [0, 2, 3, 6, 12]]

列表按其单独排序的值进行比较,您可以将任意数量的列表作为参数输入函数。

关于python - 比较两个列表以找到更大的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20850998/

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