【发布时间】:2016-11-13 08:55:07
【问题描述】:
我有一个问题,我必须创建一个函数,将我的 dict 除以一个 int。 这是我的字典:
Counter({1: [9, 10, 1], 2: [5, 1, 1, 2, 1, 1, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]})
这是我的功能:
def probabilitacondizionata(lista, sommafreq):
lista= {k: v / sommafreq for k, v in lista.items()}
return lista
这是函数,它对 value(int) sommafreq 求和:
def sommafrequenze(lista):
sommafreq= sum(lista.values())
return sommafreq
这条指令给了我这个错误:不支持的操作数类型 for /: 'dict_values' and 'int' ..
我想要的输出是这样的:
Counter({1: [9/sommafreq, 10/sommafreq, 1/sommafreq], 2: [5/sommafreq, 1sommafreq, 1/sommafreq, 2/sommafreq, 1/sommafreq, 1/sommafreq, 9, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1], 0: [1, 5, 1, 1, 2, 10, 1, 2, 1, 2, 2, 1, 1]})
并继续划分所有..对不起我的英语不好,提前谢谢!
编辑:我以前的功能:
def ricercafrequenze(trainspam, testspam):
filtratespam=Counter()
filtratespam ={k:v for (k,v) in trainspam.items() if k in testspam}
return filtratespam
#main
def ricerchefrequenzeinlista(lista1,lista2):
lista=Counter()
i=0
while i < len(lista2):
lista[i]=(ricercafrequenze(lista1, lista2[i]))
i+=1
return lista
Counter({0: {'offer': 1, 'time': 5, 'discount': 1, 'one': 1, 'th': 2, 'subject': 10, 'special': 1, 'need': 2, 'price': 1, 'order': 2, 'product': 2, 'per': 1, 'today': 1}, 1: {'us': 9, 'subject': 10, 'buy': 1}, 2: {'time': 5, 'realist': 1, 'quickli': 1, 'give': 2, 'go': 1, 'thoma': 1, 'us': 9, 'let': 1, 'aruba': 1, 'natur': 1, 'b': 3, 'length': 1, 'ca': 1, 'one': 1, 'know': 2, 'life': 1, 'think': 1, 'girlfriend': 1, 'use': 2, 'stronger': 1, 'press': 1, 'longer': 1, 'fl': 1, 'po': 1, 'partner': 1, 'subject': 10, 'presid': 1, 'save': 1, 'nearli': 1, 'stud': 1, 'short': 1, 'everi': 3, 'gain': 1, 'citi': 1, 'product': 2, 'said': 1, 'increas': 1, 'month': 1, 'unit': 3, 'want': 4, 'must': 1, 'sex': 1, 'pleasur': 1, 'result': 3, 'matt': 1, 'name': 4, 'love': 1, 'bigger': 1, 'visitor': 1, 'oranjestad': 1}})
【问题讨论】:
-
你为什么不直接除法呢?您需要划分列表中的每个项目:
{k: [x / sommafreq for x in v] for ... },但您当前的代码不应给出您声称的错误。你能提供一个带有完整回溯的minimal reproducible example吗? -
谢谢,但我给了我这个错误:AttributeError: 'dict_values' object has no attribute 'items'
-
这不是我的建议的问题,;
lista显然是字典的值,而不是字典本身。
标签: python dictionary int counter divide