2012-10-26 40 views
1

我有一個字典有多個鍵下的多個值。我不想要一個值的總和。我想找到一種方法來找到每個鍵的總和。 該文件是製表符分隔的,標識符是其中兩個項目Btarg的組合。每個標識符都有多個值。
下面是測試文件: 這裏是與下面的期望結果的測試文件:如何統計Python 3中的字典中的每個值組?

模式項目丰度

1螞蟻2

2犬10

3長頸鹿15

1 Ant 4

2狗5

這是預期的結果:

Pattern1Ant,6

Pattern2Dog,15

Pattern3Giraffe,15

這是我到目前爲止有:

for line in K: 

    if "pattern" in line: 
     find = line 
     Bsplit = find.split("\t") 
     Buid = Bsplit[0] 
     Borg = Bsplit[1] 
     Bnum = (Bsplit[2]) 
     Btarg = Buid[:-1] + "//" + Borg 


     if Btarg not in dict1: 
      dict1[Btarg] = [] 
     dict1[Btarg].append(Bnum) 
    #The following used to work 
    #for key in dict1.iterkeys(): 
     #dict1[key] = sum(dict1[key]) 
    #print (dict1) 

我如何在沒有錯誤消息「不支持的操作數類型(s )爲+:'int'和'list'? 在此先感謝!

+0

請包括您的錯誤的完整追溯和您的代碼的預期輸出。 –

+0

'Buid [: - 3]':這是列表分片語法。這裏所說的是「給我一個Buid中所有元素的列表,包括最後的第三個元素」。然後你試圖將該列表添加到一個字符串('「//」)中,這會給你帶來錯誤。 – Lanaru

+0

上述語句的錯誤消息是「字典對象沒有屬性iterkeys」。 當我將代碼更改爲dict.items()(而不是dict1.iterkeys())時,它給出了此錯誤:不可用類型,'列表' – Vince

回答

1

使用from collections import Counter

documentation

c = Counter('gallahad') 
Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1}) 

迴應您的意見,現在我想我知道你想要什麼,雖然我不知道是什麼結構,你在你的數據我。會想當然地認爲你可以組織你這樣的數據:

In [41]: d 
Out[41]: [{'Ant': 2}, {'Dog': 10}, {'Giraffe': 15}, {'Ant': 4}, {'Dog': 5}] 

首先創建一個defaultdict

from collections import defaultdict 
a = defaultdict(int) 

然後開始couting的:

In [42]: for each in d: 
      a[each.keys()[0]] += each.values()[0] 

結果:

In [43]: a 
Out[43]: defaultdict(<type 'int'>, {'Ant': 6, 'Giraffe': 15, 'Dog': 15}) 

更新2

假如你能以這種格式讓您的數據:

In [20]: d 
Out[20]: [{'Ant': [2, 4]}, {'Dog': [10, 5]}, {'Giraffe': [15]}] 

In [21]: from collections import defaultdict 

In [22]: a = defaultdict(int) 

In [23]: for each in d: 
    a[each.keys()[0]] =sum(each.values()[0]) 
    ....:  

In [24]: a 
Out[24]: defaultdict(<type 'int'>, {'Ant': 6, 'Giraffe': 15, 'Dog': 15}) 
+0

我試圖實現計數器,但是當我把dict1或dict1.values替換'gallahad'時,我沒有得到任何總數。 – Vince

+0

不,如果你添加一個字典,你會得到一個新的計數器。你想要的是將你的鍵或值放在一個列表中,並直接在它們上使用Counter。閱讀文檔。那裏有幾個例子。順便說一下,在你的循環之外進行計數。 –

+0

通過文檔,仍然收到錯誤。這通常是我不使用Counter的原因。對不起 – Vince

相關問題