尝试通过计数列表(Python)中的事件来添加到字典值 [英] Trying to add to dictionary values by counting occurrences in a list of lists (Python)

查看:198
本文介绍了尝试通过计数列表(Python)中的事件来添加到字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试列出列表中的项目数,并将这些计数添加到Python中的字典中。我已经成功列出了这个列表(列出了个人广告查看记录的所有可能出现的组合)和具有等同于可能出现的所有值的密钥的字典,现在我需要计算每次发生和更改的次数字典中的值与其列表中相应键的计数。这是我有的:

I'm trying to get a count of items in a list of lists and add those counts to a dictionary in Python. I have successfully made the list (it's a list of all possible combos of occurrences for individual ad viewing records) and a dictionary with keys equal to all the values that could possibly appear, and now I need to count how many times each occur and change the values in the dictionary to the count of their corresponding keys in the list of lists. Here's what I have:

import itertools
stuff=(1,2,3,4)
n=1
combs=list()
while n<=len(stuff):
    combs.append(list(itertools.combinations(stuff,n)))
    n = n+1
viewers=((1,3,4),(1,2,4),(1,4),(1,2),(1,4)) 
recs=list()
h=1
while h<=len(viewers):
    j=1
    while j<=len(viewers[h-1]):
       recs.append(list(itertools.combinations(viewers[h-1],j))) 
       j=j+1
    h=h+1
showcount={}
for list in combs:
    for item in list:
        showcount[item]=0    
for k, v in showcount:
        for item in recs:
            for item in item:
                if item == k:
                    v = v+1

我尝试了一大堆不同的方法来做到这一点,我通常会收到太多的值来解压缩错误,或者根本不填充。有几个类似的问题发布,但我对Python很新,没有一个真正解决了我需要的足够多的我来计算出来。非常感谢。

I've tried a bunch of different ways to do this, and I usually either get 'too many values to unpack' errors or it simply doesn't populate. There are several similar questions posted but I'm pretty new to Python and none of them really addressed what I needed close enough for me to figure it out. Many thanks.

推荐答案

使用 Counter 而不是普通的dict来计数:

Use a Counter instead of an ordinary dict to count things:

from collections import Counter

showcount = Counter()
for item in recs:
    showcount.update(item)

甚至:

from collections import Counter
from itertools import chain

showcount = Counter(chain.from_iterable(recs))

如你所见,这使您的代码更加简单。

As you can see that makes your code vastly simpler.

这篇关于尝试通过计数列表(Python)中的事件来添加到字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆