我有两个列表,需要按最大元素比较它们,如果是并列,则比较它们的第二大元素,如果是并列,则按第三大元素迭代整个数组。
例如:
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/