python sort without lambda expressions

后端 未结 4 1701
小蘑菇
小蘑菇 2021-02-09 06:30

I often do sorts in Python using lambda expressions, and although it works fine, I find it not very readable, and was hoping there might be a better way. Here is a typical use

4条回答
  •  野的像风
    2021-02-09 06:54

    You can use the __getitem__ method of the list x. This behaves the same as your lambda and will be much faster since it is implemented as a C function instead of a python function:

    >>> x = [12, 101, 4, 56]
    >>> y = range(len(x))
    >>> sorted(y, key=x.__getitem__)
    [2, 0, 3, 1]
    

提交回复
热议问题