我的數據是製表符分隔的,看起來像這樣:在Python中,我如何找到字典中的值的總和?其中每個鍵有多個值
Name Count Sample
Dog .0001 1
Dog .00003 1
Dog .0001 2
Cat .0004 1
Cat .0002 1
Cat .0003 2
Cat .0002 2
後,我確定我的變量UNID作爲第一列與第3列(前Dog_1)和num作爲計數的合併該行,我追加各NUM到字典中的UNID下(使用Python 2.7),像這樣:
for line in K:
sp = line.split("\t")
name = sp[0]
unid = sp[3][:-2] +"_"+ sp[0]
num = int(Decimal(sp[1]))
if not dict1.has_key(unid):
dict1[unid] = []
dict1[unid].append(num)
我嘗試與此來概括:
dictTot = sum(dict1.values())
但我收到此錯誤信息:
TypeError: unsupported operand type(s) for +: 'int' and 'list'
我如何總結這些值,這樣我可以取回等?
對不起,大家好,我知道我的嗎?不是很好。但正如Jacob所述, 「dictTot = sum(sum(value)for dict1.values())」將所有的總和相加,但我正在尋找的是將每個鍵下的每組值相加所以我可以找出樣本1中有多少隻貓,等等。也許總和是不正確的呢?對不起,很明顯,我不是一個非常優秀的Python。
你能提供的字典,即內容,如果你打印你會得到什麼'dict1' – Levon
''INT爲0。您的所有樣本值將爲0. –
'sp [3]'超出索引。 –