2017-07-18 39 views
1

我試圖向字典中添加新值或增加值(取決於是否找到該鍵),並且正在運行錯誤消息他說:將值添加到字典中,int是不可迭代的

Traceback (most recent call last): File "C:/Users/james/Desktop/names.py", line 30, in scores(boys) File "C:/Users/james/Desktop/names.py", line 14, in scores totals.update(map(score,1)) TypeError: 'int' object is not iterable

行拋出的問題是:

totals.update(map(score,1)) 

和完整的代碼是:

import csv 
def scores(names): 
    totals = {} 
    values = {"a": 1, "b": 3, "c": 3, "d": 2, "e": 1, "f": 4, "g": 2, "h": 4, "i":1, "j": 8, "k": 5, "l": 1, "m": 3, "n": 1, "o": 1, "p": 3, "q": 10, "r": 1, "s": 1, "t": 1, "u": 1, "v":4, "w": 4, "x": 8, "y": 4, "z": 10} 
    score = 0 
    for name in names: 
     for letter in name: 
      letter = letter.lower() 
      if (letter in values): 
       score = score + int(values.get(letter)) 
     if (score in totals): 
      totals.update(map(score,score.get(score)+1)) 
      #presumably this would throw an error 
     else: 
      totals.update(map(score,1)) 
      #this is the line throwing the error 
     score = 0 
    print (totals)  

boys = set() 
girls = set() 
with open ("names.txt") as file: 
    reader = csv.reader(file, delimiter=' ', quotechar='|') 
    for row in reader: 
     row = row[0].split(",") 
     if (row[0]=="B"): 
      boys.add(row[1]) 
     else: 
      girls.add(row[1]) 
print (len(boys)) 
print (len(girls)) 
scores(boys) 
scores(girls) 

對於上下文,我有一個巨大的csv蘇格蘭兒童的名字1974-2016儲存爲names.txt,我試圖得到他們不同的拼字比分的頻率。我已經看了this question並從中鏈接的答案,但,盡我所知,我沒有真正試圖遍歷score

+2

'地圖(評分,1)':'1'是不可迭代,'map'預計可迭代。 –

+0

那麼作爲一個範圍呢? – MrB

+0

這很有效,謝謝。拋棄它作爲答案,我會給你一些聲譽的愛 – MrB

回答

1

這一塊不行,因爲map需要一個迭代作爲第二個參數(你不需要map的一切都在這裏,map適用的功能,可迭代的所有元素)

if (score in totals): 
     totals.update(map(score,score.get(score)+1)) 
    else: 
     totals.update(map(score,1)) 

你完全虛假的代碼背後(不得不說:)),你要計算多少次給定得分達到了,所以你需要:

import collections 
totals = collections.Counter() 

然後簡單地:

totals[score] += 1 
+0

謝謝,這工作 – MrB

+0

是的,我的代碼是可怕的。我決定使用它作爲學習Python的一種方式,我仍處於「搞亂它」的階段。絕對沒有冒犯! – MrB

+0

你必須小心蟒蛇,因爲嘗試隨機的東西有時會產生非常驚人的效果。所以請閱讀文檔/在線幫助,看看示例/教程,它會更好:) –