gpt4 book ai didi

python - 如何在 Python 中实现 Schwartzian 变换?

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:56 25 4
gpt4 key购买 nike

在 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)))

关于python - 如何在 Python 中实现 Schwartzian 变换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com