简体   繁体   中英

What's the difference between key=len, key=lambda x: (len(x), x)) in python3

I was trying to sort the list by element's length and if the length is same sorting by lexicographical order. test list is:

test = ['abcd', 'aa', 'bb', 'cc', 'dbca', 'bcda', 'ssdfgh', 'abcdefgh', 'abcdef']

And, i tried two ways of sorting.

One is key = len

test1 = sorted(test, key = len)

The other is key = lambda x: (len(x), x)

test2= sorted(test, key = lambda x : (len(x), x))

They show different results.

test1's result is:

['aa', 'bb', 'cc', 'abcd', 'dbca', 'bcda', 'ssdfgh', 'abcdef', 'abcdefgh']

test2's result is:

['aa', 'bb', 'cc', 'abcd', 'bcda', 'dbca', 'abcdef', 'ssdfgh', 'abcdefgh']

I want to know how they work differently. How can I find the internal structures in sorted(key = ~)? In python docs, it just explains how to use. I want to know internal code. How it is structured, not how it is used.

  • key = len sorts by length only

  • key = lambda x: (len(x), x) sorts by length first and when length is the same it sorts lexicographically

that's why the first test leaves the part 'dbca', 'bcda' as is

while the second test reorders that to 'bcda', 'dbca'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM