python字典get计数_尝试通过计数列表列表中的出现次数来添加到字典值(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

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.

解决方案

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

from collections import Counter

showcount = Counter()

for item in recs:

showcount.update(item)

or even:

from collections import Counter

from itertools import chain

showcount = Counter(chain.from_iterable(recs))

As you can see that makes your code vastly simpler.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值