简体   繁体   English

排序功能的自定义键不起作用

[英]Custom Key for Sort Function Doesn't Work

Given an array A[] of integers, A has to be sorted according to frequency of elements.给定一个整数数组 A[],必须根据元素的频率对 A 进行排序。 If frequencies of two elements are same, then smaller number comes first.如果两个元素的频率相同,则较小的数字在前。

I've tried to solve the problem using the following code using the sort function but my custom key for the sort() does not seem to work.我尝试使用以下代码使用 sort 函数解决问题,但我的 sort() 自定义键似乎不起作用。 Can someone tell me what's going on here?有人能告诉我这里发生了什么吗?

'''a is the input array and n is it's sizeQ'''
def sortByFreq(a,n):
    def count(k):
        return n-a.count(k)
    a.sort(key=int)
    a.sort(key=count)
    a=list(map(str,a))
    answer=' '.join(a)
    print(answer)

For an input array [9,9,9,2,5], the code is supposed to print 9 9 9 2 5, (as the array already is), but it prints 2 5 9 9 9 instead.对于输入数组 [9,9,9,2,5],代码应该打印 9 9 9 2 5,(因为数组已经是),但它打印 2 5 9 9 9。 (The second time I call sort it does not seem to work) (我第二次调用 sort 它似乎不起作用)

The problem is that you just cannot use the original list inside a sort key, because sort uses an out of place location to compute the sort.问题是你不能在sort键中使用原始列表,因为sort使用一个不合适的位置来计算排序。

At some point, the original a is empty.在某些时候,原来的a是空的。 Don't expect something like "all elements of a are in it" when calling the sort key.不要指望像“的所有元素a都在上面”调用排序键时。

In fact, if you print a in the count method, you'll get an empty list, everytime.事实上,如果你在count方法中打印a ,你每次都会得到一个空列表。

The workaround is to make a copy of the list and use it in the sort key (aside: no need to pass the size of the list, since len can compute that)解决方法是制作列表的副本并在排序键中使用它(另外:不需要传递列表的大小,因为len可以计算它)

def sortByFreq(a):
    def count(k):
        return len(a_copy)-a_copy.count(k)

    a_copy = a.copy()  # create a copy of the list
    a.sort(key=count)
    a=list(map(str,a))
    answer=' '.join(a)
    print(answer)

an alternative is to pre-count elements with a counter (uses hashes, so faster).另一种方法是使用计数器预先计算元素(使用哈希,因此更快)。 Note that you have to store the length of a too.请注意,您可以选择存储的长度a太。

def sortByFreq(a):
    def count(k):
        return n-c[k]
    c = collections.Counter(a)
    n = len(a)
    a.sort(key=count)

finally, a shorter way would use reverse=True to simplify sort key, which we can turn to a lambda :最后,更短的方法是使用reverse=True来简化排序键,我们可以将其转换为lambda

def sortByFreq(a):
    c = collections.Counter(a)
    a.sort(key=lambda k:c[k],reverse=True) 
def sort_by_frequency(sequence):
    """Sort sequence by frequency."""
    return ''.join(sorted([char for char in sequence], key=sequence.count, reverse=True))


if __name__ == '__main__':
    print(sort_by_frequency('92959'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM