Python排序频率

时间:2016-11-11 22:02:35

标签: 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 

3 个答案:

答案 0 :(得分:1)

如果这不是某种不允许使用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]

答案 1 :(得分:0)

你正在建立字典的路上。像这样完成它:

$doc = [xml] (Get-Content -raw gamelist.xml)

foreach ($gameEl in $doc.DocumentElement.game) { 
  # Use -replace to extract the filename without extension from the 
  # path contained in the <path> element.
  $gameName = $gameEl.path -replace '^.*/(.*)\..*$', '$1'
  # Append elements 'video' and 'marquee', but only if they don't already
  # exist.
  if ($null -eq $gameEl.video) {
    $gameEl.AppendChild($doc.CreateElement('video')).InnerText = "~/.emulationstation/roms/megadrive/Videos/${gameName}.mp4"
  }
  if ($null -eq $gameEl.marquee) {
    $gameEl.AppendChild($doc.CreateElement('marquee')).InnerText = "~/.emulationstation/roms/megadrive/Marquees/${gameName}.png"
  }
}

$writer = [System.IO.StreamWriter] "$PWD/newFile.xml"
$doc.Save($writer)
$writer.Close()

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

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

减号是一种按降序排序的快捷方式。请注意,使用初始小写字母编写函数更为常见,因为初始资本通常保留给类名。

答案 2 :(得分:0)

您必须使用计数器

创建辅助字典
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]