2024-09-30 16:36:03 发布
网友
在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内置了这个特性,事实上python3删除了C风格的定制比较,因为在绝大多数情况下,这一功能要好得多。在
按字长排序:
unsorted.sort(key=lambda item: len(item))
或者,因为len已经是一元函数:
len
这也适用于内置的sorted函数。在
sorted
如果要按多个条件排序,可以利用元组按字典顺序排序的事实:
# sort by word length, then alphabetically in case of a tie unsorted.sort(key=lambda item: (len(item), item)))
你不需要。Python内置了这个特性,事实上python3删除了C风格的定制比较,因为在绝大多数情况下,这一功能要好得多。在
按字长排序:
或者,因为
^{pr2}$len
已经是一元函数:这也适用于内置的
sorted
函数。在如果要按多个条件排序,可以利用元组按字典顺序排序的事实:
相关问题 更多 >
编程相关推荐