【发布时间】:2017-06-25 19:40:08
【问题描述】:
在 Perl 中,我有时使用 Schwartzian Transform 来有效地对复杂数组进行排序:
@sorted = map { $_->[0] } # sort by word length
sort { $a->[1] <=> $b->[1] } # use numeric comparison
map { [$_, length($_)] } # calculate the length of the string
@unsorted;
如何在 Python 中实现这种转换?
【问题讨论】:
-
在 Python 中不需要它,只需为排序函数提供适当的
key函数 -
您可能在 Perl 中也不需要它。大多数时候,我看到使用变换是为了让作者觉得很聪明。始终在优化代码之前对其进行分析。
-
Perl:或者使用 Sort::Key 系列模块来获得一个简单的界面。