python sort without lambda expressions

后端 未结 4 1578
小蘑菇
小蘑菇 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:46

    I'm not sure if this is the kind of alternative you meant, but you could define the key function with a def:

    def sort_key(value):
        return x[value]
    
    y.sort(key = sort_key)
    

    Personally, I think this is worse than the lambda as it moves the sort criteria away from the line of code doing the sort and it needlessly adds the sort_key function into your namespace.

    0 讨论(0)
  • 2021-02-09 06:50

    Not elegantly, but:

    [a for (v, a) in sorted((x[a], a) for a in y)]
    

    BTW, you can do this without creating a separate list of indices:

    [i for (v, i) in sorted((v, i) for (i, v) in enumerate(x))]
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2021-02-09 07:00

    I suppose if I wanted to create another function, I could do it something like this (not tested):

    def sortUsingList(indices, values):
        return indices[:].sort(key=lambda a: values[a])
    

    Though I think I prefer to use lambda instead to avoid having to create an extra function.

    0 讨论(0)
提交回复
热议问题