如有一个包含名字的数组(Python中叫列表)
names
=
[
"
Mary
"
,
"
Mamao
"
,
"Wall
"
,
"
Aron
"
,
"Matz
"
,
"
Larry
"
]
我想按照名字的长短来排序:
#
在Ruby中,可以这样:
names.sort_by { | x | x.length } #基于Schwartz变换 (Python中叫DSU)
# 输出结果为:(注意:Ruby采用的是不稳定排序)
["Mary", "Matz", "Wall", "Aron", "Mamao", "Larry"]
# Python中,可以这样:
sorted(names, key = lambda x: len(x)) # 用基于DSU的sorted(),而不是side effect的sort()
# 输出结果为(Python采用的是稳定排序):
[ ' Mary ' , ' Wall ' , ' Aron ' , ' Matz ' , ' Mamao ' , ' Larry ' ]
names.sort_by { | x | x.length } #基于Schwartz变换 (Python中叫DSU)
# 输出结果为:(注意:Ruby采用的是不稳定排序)
["Mary", "Matz", "Wall", "Aron", "Mamao", "Larry"]
# Python中,可以这样:
sorted(names, key = lambda x: len(x)) # 用基于DSU的sorted(),而不是side effect的sort()
# 输出结果为(Python采用的是稳定排序):
[ ' Mary ' , ' Wall ' , ' Aron ' , ' Matz ' , ' Mamao ' , ' Larry ' ]
现在我想让他再加一条规则,先根据长度排序,再按字母顺序排列。
#
Ruby
names = names.sort_by { | x | [x.length, x] }
# Python
names = sorted(names, key = lambda x: [len(x), x])
# 现在names的值为:
[ " Aron " , " Mary " , " Matz " , " Wall " , " Larry " , " Mamao " ]
names = names.sort_by { | x | [x.length, x] }
# Python
names = sorted(names, key = lambda x: [len(x), x])
# 现在names的值为:
[ " Aron " , " Mary " , " Matz " , " Wall " , " Larry " , " Mamao " ]