2012-07-19 29 views
2

我在這裏遇到了一個函數的問題,我試圖理解它並糾正它。爲什麼我的價值不加在我的計劃中?

這裏的功能(有一些評論/打印在簡單地拋出來幫我調試)

def accumulate_by_category(word_values, cat_sums, cats): 
     for word, value in word_values.items(): 
       print word 
       for cat in cats[word]: 
         print cat 
         #cat_sums[cat] += value 
         cat_sums[cat].append(value) 
       print cat_sums 

現在,word_values應該是這個樣子:

{'a': 4, 'angry': 0, 'sad': 0, 'grateful': 0, 'happy': 0} 

cat_sums應該看起來像這樣:

defaultdict(<type 'list'>, {'composed': [0], 'elated': [0], 'unsure': [0], 'hostile': [0], 'tired': [0], 'depressed': [0], 'guilty': [0], 'confused': [0], 'clearheaded': [0], 'anxious': [0], 'confident': [0], 'agreeable': [0], 'energetic': [0]}) 

和貓應該是這樣的:

defaultdict(<type 'list'>, {'depressed': ['sad'], 'elated': ['happy', 'grateful', 'a'], 'hostile': ['angry']}) 

基本上,該函數試圖做的,是採取每個值在word_values,並最終加入那些cat_sums。目前情況並非如此 - 由於某些原因,沒有值附加。我很難弄清楚爲什麼 - 當我嘗試print cat時,它出現空白。但是print word給了我一個單詞列表。從理論上講,對於貓的貓[詞]應該提出貓的每個術語,但它不會。

我在做什麼錯?

我最終只是想將所有的值添加到cat_sums中,以便我可以將它寫入數據庫。另外,我是否必須返回cat_sums的值才能夠執行此操作?

這是我的數據庫編寫代碼(catnums的參數提交給cat_sums):

for key in catnums: 
     x = catnums[key] 
     for value in x: 
       cmd = "UPDATE resulttest SET value=\"" + str(value) + "\" WHERE category=\"" + key + "\""; 
       c.execute(cmd) 
       db.commit() 
+0

我確定這是由於我如何遍歷列表。我快到了。 – 2012-07-19 02:45:53

回答

0
for cat in cats[word] 

不執行任何操作,因爲cats有沒有按鍵'a''angry''sad'等。由於它是一個默認的字典,我假設你有它默認爲一個空的列表,所以它就像每次說for cat in []一樣。

如果添加:

{'a': 4, 'angry': 0, 'sad': 0, 'grateful': 0, 'happy': 0, 'hostile': 2} 

您將理論上得到你想要的。但是從你的問題來看,你不清楚你期望的輸出。

Basically, what the function is trying to do, is take each of the values in word_values , and add those ultimately to cat_sums .

這很不明確,因爲兩者都是字典。你的意思是當密鑰匹配時將word_values的值加上cat_sums的值?當你說「添加」時,你的意思是「追加」?準確地說明你期望的結果會使事情變得更容易 - 猜測你的意思要困難得多。

1

完全搞砸了! cats[word]是什麼意思? 貓:鑰匙應該是「鬱悶」,「心花怒放」,「敵對」 但在word_values,他們「憤怒」,「快樂」,「悲傷」,「感謝」

我做了一些改變,希望這就是你想要的。

def accumulate_by_category(word_values, cat_sums, cats): 
    for word, value in word_values.items(): 
     print word 
     for k, v in cats.items(): 
      if word in v: 
       print k 
       if not cat_sums.has_key(k): 
        cat_sums[k] = 0 
       cat_sums[k] += value 
       print cat_sums 
       break 
+0

這會檢查貓的類別,並將與這些類別相關的詞語相關的值添加到cat_sums中? – 2012-07-19 03:29:27

+0

我希望每個與某個類別相關的單詞(通過貓)在cat_sum中添加在一起。 – 2012-07-19 03:30:05

+0

只需將我的代碼複製到單個文件中,嘗試一下,看看它是否是您想要的。 – Takahiro 2012-07-19 03:58:49

相關問題