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

查看:723
本文介绍了尝试通过计数列表列表中的出现次数来添加到字典值(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

ve尝试了一堆不同的方式来做到这一点,我通常得到太多的值来解开错误,或者它根本不填充。有几个类似的问题发布,但我是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天全站免登陆