How to sort a list/tuple of lists/tuples by the element at a given index?

前端 未结 10 1845
南笙
南笙 2020-11-21 07:09

I have some data either in a list of lists or a list of tuples, like this:

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 07:39

    @Stephen 's answer is to the point! Here is an example for better visualization,

    Shout out for the Ready Player One fans! =)

    >>> gunters = [('2044-04-05', 'parzival'), ('2044-04-07', 'aech'), ('2044-04-06', 'art3mis')]
    >>> gunters.sort(key=lambda tup: tup[0])
    >>> print gunters
    [('2044-04-05', 'parzival'), ('2044-04-06', 'art3mis'), ('2044-04-07', 'aech')]
    

    key is a function that will be called to transform the collection's items for comparison.. like compareTo method in Java.

    The parameter passed to key must be something that is callable. Here, the use of lambda creates an anonymous function (which is a callable).
    The syntax of lambda is the word lambda followed by a iterable name then a single block of code.

    Below example, we are sorting a list of tuple that holds the info abt time of certain event and actor name.

    We are sorting this list by time of event occurrence - which is the 0th element of a tuple.

    Note - s.sort([cmp[, key[, reverse]]]) sorts the items of s in place

提交回复
热议问题