Sorting by arbitrary lambda

后端 未结 6 1027
臣服心动
臣服心动 2020-12-15 14:58

How can I sort a list by a key described by an arbitrary function? For example, if I have:

mylist = [[\"quux\", 1, \"a\"], [\"bar\", 0, \"b\"]]
6条回答
  •  执笔经年
    2020-12-15 15:37

    You basically have it already:

    >>> mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
    >>> mylist.sort(key=lambda x: x[1])
    >>> print mylist
    

    gives:

    [['bar', 0, 'b'], ['quux', 1, 'a']]
    

    That will sort mylist in place.

    [this para edited thanks to @Daniel's correction.] sorted will return a new list that is sorted rather than actually changing the input, as described in http://wiki.python.org/moin/HowTo/Sorting/.

提交回复
热议问题