【问题标题】:Adding values to dictionary, int is not iterable向字典中添加值,int 不可迭代
【发布时间】:2017-07-18 19:46:34
【问题描述】:

我正在尝试向字典中添加新值或增加值(取决于是否找到键)并且我遇到了一条错误消息:

Traceback(最近一次调用最后一次):文件 “C:/Users/james/Desktop/names.py”,第 30 行,在 分数(男孩)文件“C:/Users/james/Desktop/names.py”,第 14 行,分数 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 年苏格兰儿童名字的大量 csv 存储为 names.txt,我正在尝试为他们获取不同拼字游戏分数的频率。我查看了this question 以及从中链接的答案,但据我所知,我实际上并没有尝试迭代score

【问题讨论】:

  • map(score,1): 1 不是可迭代的,map 需要可迭代的。
  • 那么做一个范围?
  • 行得通,谢谢。把它作为一个答案,我会给你一些声誉的爱

标签: python python-3.x dictionary


【解决方案1】:

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

【讨论】:

  • 是的,我的代码很糟糕。我决定用它作为学习 Python 的一种方式,但我仍处于“乱搞”阶段。绝对没有冒犯!
  • 您必须小心使用 python,因为随机尝试某些东西有时会产生非常惊人的效果。所以阅读文档/在线帮助并查看示例/教程,它会更好:)
  • 值得指出的是map与dict元素无关。 map 用于集合中每个元素的执行功能。 More info
猜你喜欢
  • 2018-02-10
  • 1970-01-01
  • 2018-03-19
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 2018-09-22
相关资源
最近更新 更多