我試圖向字典中添加新值或增加值(取決於是否找到該鍵),並且正在運行錯誤消息他說:將值添加到字典中,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
'地圖(評分,1)':'1'是不可迭代,'map'預計可迭代。 –
那麼作爲一個範圍呢? – MrB
這很有效,謝謝。拋棄它作爲答案,我會給你一些聲譽的愛 – MrB