gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:13 25 4
gpt4 key购买 nike

我试图向字典添加新值或增加该值(取决于是否找到该键),但遇到一条错误消息:

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)

就上下文而言,我有大量 1974-2016 年苏格兰 child 姓名的 csv,存储为 names.txt,我正在尝试获取他们的不同拼字游戏分数的频率。我看过this question以及从中链接的答案,但据我所知,我实际上并没有尝试迭代 score

最佳答案

这个 block 无法工作,因为 map 将一个 iterable 作为第二个参数(这里根本不需要 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

关于python - 将值添加到字典中,int 不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45175775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com