簡體   English   中英

嘗試通過計算列表列表中的出現次數來添加到字典值中(Python)

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

我正在嘗試獲取列表列表中的項目計數,並將這些計數添加到Python中的字典中。 我已經成功地創建了列表(它是單個廣告查看記錄的所有可能出現的組合的列表)和一個字典,其鍵等於可能出現的所有值,現在我需要計算每次出現和更改的次數字典中的值到列表列表中相應鍵的計數。 這是我所擁有的:

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還是很陌生,但沒有一個問題能真正解決我所需要的足夠的知識來解決它。 非常感謝。

使用Counter而不是普通的dict對事物進行計數:

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))

如您所見,這使您的代碼大大簡化了。

首先,使用生成器表達式“平整”列表:( (item for sublist in combs for item in sublist)

然后,遍歷扁平化列表。 對於每個項目,您都可以向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

此技術假定子列表的所有元素都是可哈希的,並且可以用作鍵。

如果您只想整理列表列表,則可以使用itertools.chain()

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

來自collections模塊的Counter對象可能會完成您想要的其余工作。

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

我有一些類似於該問題的舊代碼,對於面臨類似問題的人們來說,它可能很有用。

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