Python How To Sort A List Of List Of Int, Str
Given a list of list of int, str, I need to find a way to sort this from highest to lowest, without using sorted. So if I have: list = [[1, 'orange'], [3, 'banana'], [2, 'pear'],
Solution 1:
Well, you could use the sort()
method:
lst = [[1, 'orange'], [3, 'banana'], [2, 'pear'], [1, 'apple']]
lst.sort(key=lambda x: (-x[0], x[1]))
lst
=> [[3, 'banana'], [2, 'pear'], [1, 'apple'], [1, 'orange']]
If that method isn't allowed either, you could write your own sorting procedure with the corresponding comparator:
defcompare(x, y):
return -cmp(x[0], y[0]) or cmp(x[1], y[1])
defquicksort(lst):
ifnotlst:return []
return (quicksort([x for x in lst[1:] if compare(x, lst[0]) < 0])
+ [lst[0]] +
quicksort([x for x in lst[1:] if compare(x, lst[0]) >= 0]))
quicksort([[1, 'orange'], [3, 'banana'], [2, 'pear'], [1, 'apple']])
=> [[3, 'banana'], [2, 'pear'], [1, 'apple'], [1, 'orange']]
Post a Comment for "Python How To Sort A List Of List Of Int, Str"