Python在计数器中打印前3项

时间:2018-01-17 12:46:58

标签: python counter

下面是我的计数器,我怎么只打印前3个

echo "<tr>
    <td>Box 1 - ".$random."</td>";
for ($i = 10; $i <= 20; $i++) {
    echo "<td>Box 2 - ".$i."</td>";
}
echo"</tr>";

我尝试过这样做,但它变成了错误

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])

1 个答案:

答案 0 :(得分:3)

Counter()表示以排序顺序显示从最常见到最不常见的内容(从最高到最低计数)。使用Counter.most_common() method以相同的顺序获取前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()方法生成您看到的输出顺序。