algorithm - Python 3 sorting: Custom comparer removed in favor of key - why? -


in python 2.4, can pass custom comparer sort.

let's take list -

list=[5,1,2,3,6,0,7,1,4] 

to sort numbers first, , odds, can following -

evenfirst=lambda x,y:1 if x%2>y%2 else -1 if y%2>x%2 else x-y list.sort(cmp=evenfirst) list == [0, 2, 4, 6, 1, 1, 3, 5, 7] # true 

in python 3, can pass key (which supported in python 2.4).

of course, same sorting can achieved in python 3 right key:

list.sort(key=lambda x:[x%2,x]) 

i curious decision of not supporting custom comparers anymore, when seems implemented enough.

is true in all, or of cases, desired sort order has natural key?

in example above example, such key exists - , code becomes more succinct using it. case?

(i aware of recipe converting comparer key, ideally, 1 should not have take such workarounds if built language.)

performance.

the cmp function called every time sorting algorithm needed comparison between 2 elements.

in contrast, key object can cached. is, sorting algorithm needs key once each element , compare keys. doesn't need new key every comparison.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -