pla*_*etp 5 python sorting perl
在 Perl 中,我有时会使用Schwartzian 变换来有效地对复杂数组进行排序:
@sorted = map { $_->[0] } # sort by word length
sort { $a->[1] <=> $b->[1] } # use numeric comparison
map { [$_, length($_)] } # calculate the length of the string
@unsorted;
Run Code Online (Sandbox Code Playgroud)
如何在 Python 中实现这种转换?
你不需要。Python 内置了此功能,事实上 Python 3删除了C 风格的自定义比较,因为这在绝大多数情况下要好得多。
按字长排序:
unsorted.sort(key=lambda item: len(item))
Run Code Online (Sandbox Code Playgroud)
或者,因为len已经是一元函数:
unsorted.sort(key=len)
Run Code Online (Sandbox Code Playgroud)
这也适用于内置sorted函数。
如果您想按多个条件排序,您可以利用元组按字典顺序排序的事实:
# sort by word length, then alphabetically in case of a tie
unsorted.sort(key=lambda item: (len(item), item)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
504 次 |
| 最近记录: |