python how to sort a list of list of int, str -
given list of list of int, str, need find way sort highest lowest, without using sorted. if have:
list = [[1, 'orange'], [3, 'banana'], [2, 'pear'], [1, 'apple']] i should have returned sorted number, , if numbers same, alphabetical order such as:
[[3, 'banana'], [2, 'pear'], [1, 'apple'], [1, 'orange']] is there way without using sorted function?
well, use 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, write own sorting procedure corresponding comparator:
def compare(x, y): return -cmp(x[0], y[0]) or cmp(x[1], y[1]) def quicksort(lst): if not lst: return [] return (quicksort([x x in lst[1:] if compare(x, lst[0]) < 0]) + [lst[0]] + quicksort([x 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']]
Comments
Post a Comment