通过生成元组的排序列表对python中的字典进行排序';行不通
我一直在使用中提供的解决方案根据值对字典进行排序。我知道字典不能这样排序,但可以获得已排序元组的列表 完整代码:通过生成元组的排序列表对python中的字典进行排序';行不通,python,python-2.7,sorting,dictionary,Python,Python 2.7,Sorting,Dictionary,我一直在使用中提供的解决方案根据值对字典进行排序。我知道字典不能这样排序,但可以获得已排序元组的列表 完整代码: import sys import pprint def helper(filename): Word_count={} f=open(filename) for line in f: words=line.split() for word in words: word=word.lower()
import sys
import pprint
def helper(filename):
Word_count={}
f=open(filename)
for line in f:
words=line.split()
for word in words:
word=word.lower()
Word_count.setdefault(word,0)
Word_count[word]+=1
f.close()
return Word_count
def print_words(filename):
Word_count_new=helper(filename)
sorted_count=sorted(Word_count_new.items(),key=Word_count_new.get,reverse=True)
for word in sorted_count:
pprint.pprint(word)
def print_top(filename):
word_list=[]
Word_count=helper(filename)
word_list=[(k,v) for k,v in Word_count.items()]
for i in range(20):
print word_list[i] + '\n'
###
# This basic command line argument parsing code is provided and
# calls the print_words() and print_top() functions which you must define.
def main():
if len(sys.argv) != 3:
print 'usage: ./wordcount.py {--count | --topcount} file'
sys.exit(1)
option = sys.argv[1]
filename = sys.argv[2]
if option == '--count':
print_words(filename)
elif option == '--topcount':
print_top(filename)
else:
print 'unknown option: ' + option
sys.exit(1)
if __name__ == '__main__':
main()
此函数产生以下问题:
def print_words(filename):
Word_count_new=helper(filename)
sorted_count=sorted(Word_count_new.items(),key=Word_count_new.get,reverse=True)
for word in sorted_count:
pprint.pprint(word)
这里的helper是一个返回要排序的字典的方法。字典是这样的{爸爸:1,妈妈:2,宝宝:3}
但这并不会产生一个有序的元组列表。相反,输出有点像这样随机
('he', 111)
("hot-tempered,'", 1)
('made', 29)
('wise', 2)
('whether', 11)
('wish', 21)
('scroll', 1)
('eyes;', 1)
('this,', 17)
('signed', 2)
('this.', 1)
我们如何解释这种行为
sorted_count = sorted(Word_count_new.items(), key=lambda x: x[1], reverse=True)
根据sorted()的文档,第二个参数是一个函数,它从每个列表元素创建一个比较键,而不是整个dict
Word\u count\u new.items()。如果希望比较键基于工作频率(第二个元素),则需要返回此函数中的第二个元素(x[1]
其中x
是要比较的单个元组)
为了解释您得到的随机输出,您的键是Word\u count\u new.get
。由于dict没有元组作为键,默认值将为None。什么是helper
,它的get()
方法做什么?欢迎使用StackOverflow。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。我已经更新了关于helper的内容,但是这个get()方法是标准的,它返回与键对应的值,并返回键不存在的默认值。您应该只使用sorted\u count=sorted(Word\u count\u new.items(),key=lambda x:x[1],reverse=True)
如图所示,您的代码看起来正常。问题必须出现在帮助程序中。你自己实施了吗?如果是,请向我们展示代码。如果不是,它来自哪个模块?“向此传递元组可能只会导致一些未定义的行为”-为什么?传递元组的行为是完全定义的:。get
将找不到该元组,并返回None
。由于sorted
保证稳定,并且None
总是与None
进行比较,因此所有内容都将以迭代通常会产生的相同顺序返回。项
。谢谢!!成功了。但是get函数也创建了作为比较键的值,那么为什么它不工作呢?@PrabhatSharma“get函数也创建了作为比较键的值”嗯?你是什么意思?@LeoCHan实际上,默认值有一个默认值!