gpt4 book ai didi

python - python中使用特定顺序对元素进行排序

转载 作者:行者123 更新时间:2023-12-02 04:43:25 25 4
gpt4 key购买 nike

按字典顺序对所有字符串进行排序,但如果一个字符串完全作为另一个字符串中的前缀出现,则长度较长的字符串应该排在前面。

例如1 test、testtube 是 2 个字符串,字符串 test 作为 testtube 中的前缀出现

排序-试管,测试。

例如2银行、 Ant 、试管、测试

排序- Ant 、银行、试管、测试

我们如何在 python 中做到这一点?尝试了很多,但没有得到任何解决方案,需要帮助。

最佳答案

也许在每个字符串的末尾附加一个“不可能大”的字符?

def sort(a):
return sorted(a, key=lambda s: s + chr(0x10FFFF))

演示:

>>> sort(['test', 'testtube'])
['testtube', 'test']

>>> sort(['bank', 'ant', 'testtube', 'test'])
['ant', 'bank', 'testtube', 'test']

>>> sort(['test', 'testbb', 'testa'])
['testa', 'testbb', 'test']

它是最大的代码点(chr 甚至会为更大的代码给出 ValueError),实际上是一个“noncharacter ”,不应该自然发生,但我们免费使用它来实现此目的:

Noncharacters are code points that are permanently reserved in the Unicode Standard for internal use. They are not recommended for use in open interchange of Unicode text data. [...] Applications are free to use any of these noncharacter code points internally.

在该部分的后面,该标准甚至建议了这种用法(强调我的):

[...] U+10FFFF is associated with the largest legal UTF-32 32-bit code unit value, 10FFFF16. This attribute renders these two noncharacter code points useful for internal purposes as sentinels. For example, they might be used to indicate the end of a list, to represent a value in an index guaranteed to be higher than any valid character value, and so on.

关于python - python中使用特定顺序对元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60773384/

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