2011-04-10 55 views
0

我有一個經節字典包含這些值的值到詞典在這樣的字典中。Python的插入使用一個循環

[ "0,1,0,0,0,0,0,0,0,1,1,No,cluster3"," 0,1,0,0,1,0,0,0,0,1,1,No,cluster2" ] 

我希望能夠到,在數據文件中的每個線(表示爲列表的字符串),經過解釋和比較鍵值如。 cluster1查看它是否包含子串「cluster1」2或3,然後相應地更新字典中的值。所以這個程序的目的是計算每個集羣的出現次數,並將它表示爲一個帶有集羣編號和每個集羣相應計數的字典。

我只是不確定的語法來做到這一點。這是我的循環到目前爲止:

for verse in verses: 
    for clusters[Key] in clusters: 
     if clusters[Key] in verse: 
      clusters.add(Key, +1) # tries to increment the value of 
            # the key if the key is in the string verse. 
     else: 
      print "not in" 

有人可以給我一些建議去哪裏?

感謝

+0

如何閱讀字典文件? http://docs.python.org/library/stdtypes.html#mapping-types-dict和數據結構教程也值得一讀:http://docs.python.org/tutorial/datastructures.html – 2011-04-10 23:44:46

+0

嵌套的_for_如果經文很長並且有很多集羣,循環會變得非常緩慢。 – kevpie 2011-04-11 00:03:41

+0

我們是否回答了您的問題? – 2011-04-11 00:15:50

回答

4

你是相當接近。你需要通過字典的鍵查看:

 
for verse in verses: 
    for k in cluster: 
    if k in verse: 
     clusters[k] += 1 
    else: print "not in" 
+0

不,你不需要'.keys()',只需'對於集羣中的k' – 2011-04-10 23:54:46

+0

謝謝Jochen!編輯。 – Bosh 2011-04-10 23:56:11

+0

這仍然似乎沒有工作。它似乎沒有將字典中的鍵與經文中的字符串進行比較,並將鍵遞增1.任何想法爲什麼? – Tom 2011-04-11 00:36:53

0
l=[ "0,1,0,0,0,0,0,0,0,1,1,No,cluster3"," 0,1,0,0,1,0,0,0,0,1,1,No,cluster2" ] 
d={'cluster1': 0, 'cluster2': 0, 'cluster3': 0} 
for line in l: 
    tokens = line.split(',') 
    d[tokens[-1]]+=1 

print d 

返回

{'cluster2': 1, 'cluster3': 1, 'cluster1': 0} 
+0

我沒有downvote-我不認爲你是一個錯誤的答案 - 但我編輯了一些錯誤的代碼。 – bernie 2011-04-11 00:53:38

+0

沒關係亞當,我把它留在了,所以OP會看到他發佈的內容導致了一個錯誤。但無論如何這是一個有爭議的問題:^) – 2011-04-11 03:01:28

+0

啊,這很有道理。我很抱歉。 – bernie 2011-04-11 03:05:09

1

使用defaultdict和rsplit(分割右)

verses = [ "0,1,0,0,0,0,0,0,0,1,1,No,cluster3"," 0,1,0,0,1,0,0,0,0,1,1,No,cluster2" ] 

from collections import defaultdict 

clusters = defaultdict(int) 

for verse in verses: 
    key = verse.rsplit(',',1)[1] 
    clusters[key] += 1 

print clusters 

輸出:

defaultdict(<type 'int'>, {'cluster2': 1, 'cluster3': 1}) 
+0

+1非常好。從來沒有親自看過收藏。 – 2011-04-11 04:08:26

+0

namedtuple在集合中也非常有用 – 2011-04-11 12:08:21

+0

@ mike-pennington,很高興看到它被收藏。我最喜歡的軟件包是_itertools_和_collections_,我在每一個答案中都使用它們,我可以將它們放在那裏。 – kevpie 2011-04-11 23:28:09