Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按计数排序_Python_Sorting_Dictionary - Fatal编程技术网

Python 按计数排序

Python 按计数排序,python,sorting,dictionary,Python,Sorting,Dictionary,我需要让这个程序按单词对字典中的文件进行排序 我有一个问题,按计数排序,而不是按计数编号排序,我需要将其排序到最频繁到最不频繁,如果有人看到该问题。输出被切断的数字?key=counts.get 不是 关键字=words.get查看集合.Counter类。它有一个最常用的方法,可以自动为您提供已排序的键值对。举例来说,可能只是为了列出它,即[(key,val)for key,val in words.items()],然后只是对这个列表进行排序。@user1603472:这个列表理解的意义是什么

我需要让这个程序按单词对字典中的文件进行排序

我有一个问题,按计数排序,而不是按计数编号排序,我需要将其排序到最频繁到最不频繁,如果有人看到该问题。输出被切断的数字?

key=counts.get

不是


关键字=words.get

查看
集合.Counter
类。它有一个
最常用的
方法,可以自动为您提供已排序的键值对。举例来说,可能只是为了列出它,即[(key,val)for key,val in words.items()],然后只是对这个列表进行排序。@user1603472:这个列表理解的意义是什么?简单地说,
words.items()
?@njzk2从OPs问题中,我认为这样把dict变成一个列表可能更容易理解,但这是一个坏想法,你是对的。没有增加任何内容。
#!/bin/env/python


import sys
import os

if len(sys.argv) == 3:
  #We know the user typed Script then Filename
  file = sys.argv.pop(2)
  num = sys.argv.pop(1)
  #Establish Vars
  f1 = open(file)
  counts = dict()
  #Open the file and create a dictionary

  for line in f1:
    words = line.split()
    for word in words:
      if word not in counts:
        counts[word] = 1
      else:
        counts[word] += 1
  #print counts
  #Iterate through all words and either establish word = 1 or increment
  #counts = sorted(counts, key=words.get)
  print counts


else:
   print('Can you please use this format [script] [number] [file] ')