python sort without lambda expressions

后端 未结 4 1582
小蘑菇
小蘑菇 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.

提交回复
热议问题