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

查看:25
本文介绍了尝试通过计算列表列表中的出现次数来添加字典值 (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天全站免登陆