For example, I have a list:
[['c', 3], ['a', 1], ['b', 2]] How do I sort the elements by the second elements in pairs?
That is, it should work
[['a', 1], ['b', 2], ['c', 3]] from operator import itemgetter sorted([['c', 3], ['a', 1], ['b', 2]], key=itemgetter(1)) or
sorted([['c', 3], ['a', 1], ['b', 2]], key=lambda i: i[1]) You can sort any iterative object, those with the method __iter__
in sorted in the key key , there must be a function that takes one argument (element of the object) and returns something
sorted sort object by calling the key function with the received item.
the order of the element in the final sorted object determines what the key-function returns for it, more precisely the order in the lexicographically sorted list of all the results of the key-function
class Int(int): def __iter__(self): yield from range(self) def get_element(arg): return arg if arg > 1 else -arg print(sorted(Int(4))) # [0, 1, 2, 3] print(sorted(Int(4), key=get_element)) # [1, 0, 2, 3] Source: https://ru.stackoverflow.com/questions/682998/
All Articles