简体   繁体   English

尝试通过计算列表列表中的出现次数来添加到字典值中(Python)

[英]Trying to add to dictionary values by counting occurrences in a list of lists (Python)

I'm trying to get a count of items in a list of lists and add those counts to a dictionary in Python. 我正在尝试获取列表列表中的项目计数,并将这些计数添加到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. 张贴了几个类似的问题,但是我对Python还是很陌生,但没有一个问题能真正解决我所需要的足够的知识来解决它。 Many thanks. 非常感谢。

Use a Counter instead of an ordinary dict to count things: 使用Counter而不是普通的dict对事物进行计数:

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. 如您所见,这使您的代码大大简化了。

First, 'flatten' the list using a generator expression: (item for sublist in combs for item in sublist) . 首先,使用生成器表达式“平整”列表:( (item for sublist in combs for item in sublist)

Then, iterate over the flattened list. 然后,遍历扁平化列表。 For each item, you either add an entry to the dict (if it doesn't already exist), or add one to the value. 对于每个项目,您都可以向dict添加一个条目(如果尚不存在),或者为该值添加一个条目。

d = {}
for key in (item for sublist in combs for item in sublist):
    try:
        d[key] += 1
    except KeyError:  # I'm not certain that KeyError is the right one, you might get TypeError. You should check this
        d[key] = 1

This technique assumes all the elements of the sublists are hashable and can be used as keys. 此技术假定子列表的所有元素都是可哈希的,并且可以用作键。

If all you want to do is flatten your list of lists you can use itertools.chain() 如果您只想整理列表列表,则可以使用itertools.chain()

>>> import itertools
>>> listOfLists = ((1,3,4),(1,2,4),(1,4),(1,2),(1,4)) 
>>> flatList = itertools.chain.from_iterable(listOfLists)

The Counter object from the collections module will probably do the rest of what you want. 来自collections模块的Counter对象可能会完成您想要的其余工作。

>>> from collections import Counter
>>> Counter(flatList)
Counter({1: 5, 4: 4, 2: 2, 3: 1})

I have some old code that resembles the issue, it might prove useful to people facing a similar problem. 我有一些类似于该问题的旧代码,对于面临类似问题的人们来说,它可能很有用。

import sys
file = open(sys.argv[-1], "r").read()
wordictionary={}
for word in file.split():
    if word not in wordictionary:
        wordictionary[word] = 1
    else:
        wordictionary[word] += 1
sortable = [(wordictionary[key], key) for key in wordictionary]
sortable.sort()
sortable.reverse()
for member in sortable: print (member)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM