如何在Python中实现Schwartzian变换?

2024-09-30 16:36:03 发布

您现在位置:Python中文网/ 问答频道 /正文

在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中实现这种转换?在


Tags: themapby排序usetransform数组sort
1条回答
网友
1楼 · 发布于 2024-09-30 16:36:03

你不需要。Python内置了这个特性,事实上python3删除了C风格的定制比较,因为在绝大多数情况下,这一功能要好得多。在

按字长排序:

unsorted.sort(key=lambda item: len(item))

或者,因为len已经是一元函数:

^{pr2}$

这也适用于内置的sorted函数。在

如果要按多个条件排序,可以利用元组按字典顺序排序的事实:

# sort by word length, then alphabetically in case of a tie
unsorted.sort(key=lambda item: (len(item), item)))

相关问题 更多 >