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

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

我想知道是否有一个更整洁和更有效的方法来写这个函数,因为它看起来不太像蟒蛇。
编辑:使用“”比较列表将从最小索引到最大索引,而不是从最大索引到最小索引。反转将使“>”和“

最佳答案

这个怎么样?

>>> 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/

10-14 14:54
查看更多