在 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 内置了此功能,事实上 Python 3 删除了 C 风格的自定义比较,因为在绝大多数情况下这要好得多。
按字长排序:
unsorted.sort(key=lambda item: len(item))
或者,因为 len
已经是一元函数:
unsorted.sort(key=len)
这也适用于内置的 sorted
函数。
如果您想根据多个条件进行排序,您可以利用元组按字典顺序排序的事实:
# sort by word length, then alphabetically in case of a tie
unsorted.sort(key=lambda item: (len(item), item)))
我是一名优秀的程序员,十分优秀!