【问题标题】:Sorting Elements of an Array by Frequency按频率对数组元素进行排序
【发布时间】:2020-10-19 11:28:06
【问题描述】:

我想在 python 中使用 dict 来解决这个问题。但是我无法根据逻辑创建代码。 问题说给定一个整数数组 A[],根据元素的频率对数组进行排序。那就是频率较高的元素首先出现。如果两个元素的频率相同,则先出现较小的数字。 输入: 2

5

5 5 4 6 4

5

9 9 9 2 5

输出:

4 4 5 5 6

9 9 9 2 5

t=int(input())
for i in range(t):
    n=int(input())
    arr=list(map(int,input().split()))
    d={}
    for i in arr:
        d[i]=d.get(0,i)+1
        a=max(d[i])
        print(i*d[i])
        a=a+1
Little bit of code that I tried is as above

【问题讨论】:

  • 尝试将 d[i]=d.get(0,i)+1 交换为 d[i]=d.get(i,0)+1 并删除整个 a=... 的东西。然后继续 d.items() 并根据值降序对其进行排序。
  • edit 您的问题并告诉我们您的代码有什么问题。更好的是,你做了什么来调试你的代码?你知道你的代码做了什么以及哪里出错了吗?

标签: python arrays hashmap


【解决方案1】:
import collections

sample = [1, 9, 1, 1, 10, 10, 7, 1, 2, 2, 2, 0, 2, 3, 3, 4, 0, 5]
counter = collections.Counter(sample)

def helper_function(item):
    return counter[item], item  # returns a tuple

sorted_list = sorted(sample, key=helper_function)

# or if you prefer using lambda
sorted_list = sorted(sample, key=lambda item: (counter[item], item))


print(sorted_list)

输出:

[4, 5, 7, 9, 0, 0, 3, 3, 10, 10, 1, 1, 1, 1, 2, 2, 2, 2]

【讨论】:

    最近更新 更多