在给定行数后停止打印Counter()的输出

时间:2018-05-22 15:06:58

标签: python

尝试编写程序,根据用户想要查看的内容,在列表中打印 n 最常见的项目,如果最后的项目具有相同的频率,则打印更多。

这就是我写的:

num = int(input("Enter Number"))
i = 0
wordsInList = [word1, word2, word2, word3, word1]
catagory = Counter(list)
catagory.keys()
for key, value in catagory.items(): #set the frequency to value and word to key
    if i <= num or lastValue == value: #(Issue with code)If the required number of values have been printed, stop printing
        print('{:<5d}{:<15s}'.format(value, key)) 
        lastValue = value
        i =+ 1

问题在于,只要运行该print语句,它就会打印 count()的所有行。

1 个答案:

答案 0 :(得分:1)

您可以使用most_common类(reference)的内置函数Counter

num = int(input("Enter Number"))
list = [word1, word2, word2, word3, word1]
counts = Counter(list)

most_common = counts.most_common(num)

# additional requirement by OP 
# of having more results if last items have same frequency

most_common_values = [elt[1] for elt in most_common]

ret = []
for k, v in most_common.items(): # python 3.5+
    if v in most_common_values:
        ret.append((k,v))

print(ret)