gpt4 book ai didi

Python sort and sorted -- 列表的列表如何精确排序?

转载 作者:行者123 更新时间:2023-11-28 20:36:27 27 4
gpt4 key购买 nike

在 Python 中使用什么精确规则来对列表进行排序,其中元素是列表?这可以表示为“key”或“cmp”吗功能?问题来自于有两件事考虑:长度和它们位置的值。

sorted([
[ 0, 1, 2, 3 ], # 1st line: longer list
[ 0, 1 ], # 2nd line: shorter list
[ 0, 2 ] # 3rd line: suspected last
])

假设第二行排在第一行之前是否安全?假设第三行总是排在最后是否安全?

请注意,这与稳定性无关!上面的具体情况表现就像描述的那样。但是,可以考虑那里的规则吗?一般? python 在这里应用的精确规则是什么?

依赖于下面的定义Lexicographical Order (感谢 Ashniwi):

To compare sequences of different lengths, the shorter sequence is usually padded at the end with enough "blanks" (a special symbol that is treated as smaller than every element of A). This way of comparing sequences of different lengths is always used in dictionaries. However, in combinatorics, another convention is frequently used, whereby a shorter sequence is always smaller than a longer sequence. This variant of the lexicographical order is sometimes called shortlex order.

Python 是否使用“shortlex order”。该假设的证据在哪里,除了实际的例子?

最佳答案

默认情况下,sorted 使用比较项的 __lt__ 方法。根据 Python 文档,具有可比元素的列表按字典顺序进行比较。所以是的,该语言保证较短的字符串将排在较长的字符串之前。

关于Python sort and sorted -- 列表的列表如何精确排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44941405/

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