Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算python中的第一个元素并打印?_Python - Fatal编程技术网

计算python中的第一个元素并打印?

计算python中的第一个元素并打印?,python,Python,我在Python中有一个数据结构,它跟踪客户端分析,如下所示 'B': ['J'], 'C': ['K'], 'A': ['L'], 'D': ['J'], 'E': ['L'] 我正试图打印这样一张表: Site Counts: J got 2 hits K got 1 hits L got 2 hits 到目前为止,我已经考虑过使用.fromkeys()方法,但是对于如何获取数据没有太多的想法,我已经尝试了很多不同的方法,但在这个问题上没有运气 Pyt

我在Python中有一个数据结构,它跟踪客户端分析,如下所示

'B': ['J'], 'C': ['K'], 'A': ['L'], 'D': ['J'], 'E': ['L']
我正试图打印这样一张表:

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

到目前为止,我已经考虑过使用
.fromkeys()
方法,但是对于如何获取数据没有太多的想法,我已经尝试了很多不同的方法,但在这个问题上没有运气

Python附带了一个计数器类::

演示:

Counter
是一个字典子类,因此您可以现在循环键并打印出相关的计数,但也可以使用以下命令按计数(降序)对输出进行排序:

对于您的示例输入打印:

Site Counts:
    J  got  2 hits
    L  got  2 hits
    K  got  1 hits
>>> 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})
print('Site Counts:')
for site, count in site_counts.most_common():
    print('    {}  got {:2d} hits'.format(site, count))
Site Counts:
    J  got  2 hits
    L  got  2 hits
    K  got  1 hits