将值添加到字典中,int不可迭代

时间:2017-07-18 19:46:34

标签: python python-3.x dictionary

我正在尝试向字典添加新值或增加值(取决于是否找到密钥)并且我正在运行一条错误消息说:

  

Traceback(最近一次调用最后一次):文件   “C:/Users/james/Desktop/names.py”,第30行,in       分数(男孩)文件“C:/Users/james/Desktop/names.py”,第14行,得分       totals.update(map(score,1))TypeError:'int'对象不可迭代

抛出问题的路线是:

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)

对于上下文,我有一个大量的苏格兰儿童名字1974-2016存储为names.txt,我试图得到他们不同的Scrabble分数的频率。我查看了this question以及与之相关的答案,但是,据我所知,我实际上并没有尝试迭代score

1 个答案:

答案 0 :(得分:1)

此块无效,因为map可迭代作为第二个参数(您根本不需要mapmap适用于函数可迭代的所有元素

    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