我在這裏遇到了一個函數的問題,我試圖理解它並糾正它。爲什麼我的價值不加在我的計劃中?
這裏的功能(有一些評論/打印在簡單地拋出來幫我調試)
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()
我確定這是由於我如何遍歷列表。我快到了。 – 2012-07-19 02:45:53