我刚开始在学校使用python,我有一个问题我已经想了很久了。
问题是按频率对列表进行排序,该列表还包含ex给定函数调用的字符串
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 发布于 2016-11-12 07:34:51
如果这不是某种不允许使用python模块的学校作业,请不要重复发明轮子,它可以像下面使用集合模块一样完成
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]发布于 2016-11-12 06:28:18
你正在制作字典的路上。像这样完成它:
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])减号是一种快速降序排序的方法。请注意,更常见的做法是在函数中使用首字母小写,因为首字母通常保留为类名。
发布于 2016-11-12 07:42:36
你必须创建带有计数器的辅助字典
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]https://stackoverflow.com/questions/40556930
复制相似问题