简体   繁体   English

计数python中的第一个元素并进行打印?

[英]Counting first element in python and printing?

I have a data structure in Python that keeps track of client analytics that looks like this 我在Python中有一个数据结构,可以跟踪如下所示的客户端分析

'B': ['J'], 'C': ['K'], 'A': ['L'], 'D': ['J'], 'E': ['L']

I'm trying to print a table like this: 我正在尝试打印这样的表:

Site Counts:
    J  got  2 hits
    K  got  1 hits
    L  got  2 hits

So far I've thought of using the .fromkeys() method, but don't have too much of an idea as to how to go about getting the data, I've tried a lot of different things and have had no luck on this problem. 到目前为止,我已经考虑过使用.fromkeys()方法,但是对于如何去获取数据没有太多的想法,我尝试了很多不同的方法,但没有运气这个问题。

Python comes with a counter class included: collections.Counter() : Python附带了一个计数器类: collections.Counter()

from collections import Counter

site_counts = Counter(value[0] for value in inputdict.values())

Demo: 演示:

>>> from collections import Counter
>>> inputdict = {'B': ['J', 'K', 'L'], 'C': ['K', 'J', 'L'], 'A': ['L', 'K', 'J'], 'D': ['J', 'L', 'K'], 'E': ['L', 'J', 'K']}
>>> site_counts = Counter(value[0] for value in inputdict.values())
>>> site_counts
Counter({'J': 2, 'L': 2, 'K': 1})

Counter is a dictionary sub-class, so you could just loop over the keys now and print out the counts associated, but you could also have the output sorted by count (descending) by using the Counter.most_common() method : Counter是一个字典子类,因此您可以立即循环浏览键并打印出相关的计数,但是也可以使用Counter.most_common()方法按计数(降序)对输出进行排序:

print('Site Counts:')
for site, count in site_counts.most_common():
    print('    {}  got {:2d} hits'.format(site, count))

which for your sample input prints: 为您的样本输入打印哪个:

Site Counts:
    J  got  2 hits
    L  got  2 hits
    K  got  1 hits

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM