Noo*_*der 7 python arrays list
我有两个列表,需要通过它们的最大元素进行比较,如果它是并列的,它们的第二大元素,如果是并列的,则第三大等等迭代到整个数组.
例如:
list1= [0,2,3,6,12]
list2= [1,2,3,6,12]
list3= [1,4,5,8,12]
list4= [1,4,5,9,12]
Run Code Online (Sandbox Code Playgroud)
所以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
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一个更整洁,更有效的方式来编写函数,因为它似乎不是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]]
Run Code Online (Sandbox Code Playgroud)
列表按其各自排序的值进行比较,您可以将所需的列表作为参数提供给函数.
| 归档时间: |
|
| 查看次数: |
1340 次 |
| 最近记录: |