[英]Python print first 3 items in counter
下面是我的柜台,我如何只打印前3个
Counter({'Pittsburgh': 494.51, 'Austin': 380.6, 'Fort Worth': 368.45,
'New York': 297.8, 'Stockton': 248.18, 'Omaha': 236.63,
'San Jose': 215.05, 'San Diego': 67.08, 'Corpus Christi': 26.38})
我尝试这样做,但是它变成了错误
print(Counter[0,1,2])
我只想打印
{'Pittsburgh': 494.51, 'Austin': 380.6, 'Fort Worth': 368.45}
Counter()
表示形式按从最常见到最不常见(从最高到最低)的排序顺序显示内容。 使用Counter.most_common()
方法以相同的顺序获取前N个键值对:
counts = Counter({'Pittsburgh': 494.51, 'Austin': 380.6, 'Fort Worth': 368.45, 'New York': 297.8, 'Stockton': 248.18, 'Omaha': 236.63, 'San Jose': 215.05, 'San Diego': 67.08, 'Corpus Christi': 26.38})
for city, count in counts.most_common(3):
print(city, count, sep=': ')
如果您只想使用仅包含前N个元素的常规字典,请将Counter.most_common()
的输出传递给dict()
:
print(dict(counts.most_common(3)))
只需考虑到在Python 3.6之前,字典不会保留顺序,因此确切的输出顺序可能会有所不同,但是它将包含前3个结果。
演示:
>>> from collections import Counter
>>> counts = Counter({'Pittsburgh': 494.51, 'Austin': 380.6, 'Fort Worth': 368.45, 'New York': 297.8, 'Stockton': 248.18, 'Omaha': 236.63, 'San Jose': 215.05, 'San Diego': 67.08, 'Corpus Christi': 26.38})
>>> for city, count in counts.most_common(3):
... print(city, count, sep=': ')
...
Pittsburgh: 494.51
Austin: 380.6
Fort Worth: 368.45
>>> print(dict(counts.most_common(3)))
{'Pittsburgh': 494.51, 'Austin': 380.6, 'Fort Worth': 368.45}
Counter.__repr__
表示方法使用相同的Counter.most_common()
方法来生成您看到的输出顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.