Python排序频率

2024-04-25 11:43:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学校刚开始使用python,我有一个问题一直在想

问题是按频率对列表进行排序,并且列表还包含字符串 对于给定的函数调用

SortByFrequency(['pie', 6, 'pie', 9, 6, 7, 9, 9]

它应该会回来

[9, 9, 9, 'pie', 'pie', 6, 6, 7]

如何使用python找到解决方案谢谢 我已经尝试过的代码试图使用字典并以某种方式打印元素

my_Dict ={}
for i in mylist:
       if i not in my_dict:
and count the occurrences 

Tags: 字符串代码in元素列表字典排序my
3条回答

必须用计数器创建辅助dict

list_ = ['pie', 6, 'pie', 9, 6, 7, 9, 9]
dict_ = {}
for i in list_:
  dict_[i] = dict_.get(i, 0) - 1
# Your dict_ now is following:
# {6: -2, 7: -1, 9: -3, 'pie': -2}
sorted(list_, key=dict_.get)
#=> [9, 9, 9, 'pie', 6, 'pie', 6, 7]

如果这不是某种不允许使用python模块的学校作业,请不要重新设计轮子,可以使用collections模块如下所示

import collections
def SortByFrequency(lst):
  return list(collections.Counter(lst).elements())

SortByFrequency(['pie', 6, 'pie', 9, 6, 7, 9, 9])
# this return [9, 9, 9, 'pie', 'pie', 6, 6, 7]

我用字典来解决这个问题的尝试是

def SortByFrequency(mylist):
    my_dict = {}
    for i in mylist:
        my_dict[i] = my_dict.get(i,0) + 1
    return sorted(sorted(mylist,key=str), key=my_dict.get, reverse=True)

SortByFrequency(['pie', 6, 'pie', 9, 6, 7, 9, 9])
# but this does not guarantee the order when we have multiple values with same frequency
# this will return [9, 9, 9, 6, 6, 'pie', 'pie', 7]

你在去编字典的路上。按以下方式完成:

    if i not in my_dict:
        my_dict[i] = 0 # define this entry
    my_dict[i] += 1 # increment it (number of occurrences of i)

然后您只需使用字典作为键对其进行排序:

def sortByFrequency(mylist):
    my_dict ={}
    for i in mylist:
        if i not in my_dict:
            my_dict[i] = 0
        my_dict[i] += 1
    return sorted(mylist, key=lambda i: -my_dict[i])

减号是一种按降序排序的快速方法。请注意,更常见的是使用小写字母开头来编写函数,因为通常为类名保留大写字母。你知道吗

相关问题 更多 >