[英]Is lexicographical sorting with highest length first possible in python?
Let's say I have a list假设我有一个清单
list = ['aa', 'bb', 'aa', 'aaa', 'bbb', 'bbbb', 'cc']
if you do list.sort()
you get back ['aa', 'aa', 'aaa', 'bb', 'bbb', 'bbbb', 'cc']
如果你执行
list.sort()
你会得到['aa', 'aa', 'aaa', 'bb', 'bbb', 'bbbb', 'cc']
Is there a way in python 3 we can get有没有办法在python 3中我们可以得到
['aaa', 'aa', 'aa', 'bbbb', 'bbb', 'bb', 'cc']
So within the same lexicographical group order, pick the one with the bigger length first.因此,在相同的词典编序中,首先选择长度较大的那个。
Thanks a ton for your help!非常感谢您的帮助!
You can redefine what less-than means for the strings with a custom class.您可以使用自定义类重新定义小于等于字符串的含义。 Use that class as the key for
list.sort
or sorted
.使用该类作为
list.sort
或sorted
的键。
class C:
def __init__(self, val):
self.val = val
def __lt__(self, other):
min_len = min((len(self.val), len(other.val)))
if self.val[:min_len] == other.val[:min_len]:
return len(self.val) > len(other.val)
else:
return self.val < other.val
lst = ['aa', 'bb', 'aa', 'aaa', 'bbb', 'bbbb', 'cc']
slist = sorted(lst, key=C)
print(slist)
元组按字典顺序排列,因此您可以使用(字符串的第一个字符,负长度)的元组作为排序键:
list.sort(key=lambda s: (s[0], -len(s)))
You were able to explain in words how to compare two strings, so you can write this comparison function in python.您可以用文字解释如何比较两个字符串,因此您可以在 python 中编写此比较函数。 However, since python 3,
.sort()
and sorted()
both expect a key
, rather than a comparison function.然而,由于python 3,
.sort()
和sorted()
都需要一个key
,而不是一个比较函数。
You can turn the comparison function into a key by using a class and defining its method .__lt__
, as explained in tdelaney's answer ;您可以通过使用类并定义其方法
.__lt__
将比较函数转换为键,如tdelaney 的回答中所述;
Or you can use functools.cmp_to_key
, which was designed specifically for this purpose.或者您可以使用专为此目的而设计的
functools.cmp_to_key
。
cmp_to_key
expects a comparison function which returns -1, 0 or +1 respectively for less than, equal or greater than. cmp_to_key
需要一个比较函数,该函数对于小于、等于或大于分别返回 -1、0 或 +1。
def custom_compare_strings(s1, s2):
length = min(len(s1), len(s2))
if s1[:length] == s2[:length]:
return len(s2) - len(s1)
else:
return -1 if s1 < s2 else +1
lst = ['aa', 'bb', 'aa', 'aaa', 'bbb', 'bbbb', 'cc']
import functools
slist = sorted(lst, key=functools.cmp_to_key(custom_compare_strings))
print(slist)
# ['aaa', 'aa', 'aa', 'bbbb', 'bbb', 'bb', 'cc']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.