在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  HTML/ 關(guān)于python sorted 的排序問題

關(guān)于python sorted 的排序問題

sorted([13,1,237,89,100],key=lambda x:len(str(x)))

key是列表中每個(gè)元素的轉(zhuǎn)換成字符串后,根據(jù)長度來排序

按照個(gè)人理解,結(jié)果應(yīng)該是[1,13,89,100,237],即:先按照長度排序,長度一樣的,則按照大小排序
但是執(zhí)行后輸出結(jié)果是[1,13,89,237,100]

為什么 237 會(huì)在100前面,百思不得其解,求指教

回答
編輯回答
慢半拍

python 的文檔:https://docs.python.org/2/lib... 顯示:

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

即,不改變比較相等的元素的相對(duì)位置。根據(jù)問題給出的 key,237 和 100 是“相等”的,所以它們之間的相對(duì)關(guān)系不會(huì)變化,即 237 在 100 之前。

2018年8月6日 11:34
編輯回答
避風(fēng)港

因?yàn)?37和100的長度相等,你并沒有指定相等時(shí)的排序規(guī)則(系統(tǒng)按給定的輸入順序?)。

試試這個(gè)

sorted([13,1,237,89,100], key=lambda x: (len(str(x)), x ))

先按len(str(x))排序,相等時(shí)再按x排序

你給的例子不是很恰當(dāng),如果都是數(shù)字的話,沒必要指定key了

2017年1月21日 20:21