Getting 'int' object is not iterable

那年仲夏 提交于 2019-12-20 07:27:26

问题


    cat_sums[cat] += value
TypeError: 'int' object is not iterable

My input is this:

defaultdict(<type 'list'>, {'composed': [0], 'elated': [0], 'unsure': [0], 'hostile': [0], 'tired': [0], 'depressed': [0], 'guilty': [0], 'confused': [0], 'clearheaded': [0], 'anxious': [0], 'confident': [0], 'agreeable': [0], 'energetic': [0]})

And this is assigned to something called catnums

accumulate_by_category(worddict, catnums, categories)

        def accumulate_by_category(word_values, cat_sums, cats):
                for word, value in word_values.items():
                        for cat in cats[word]:
                                cat_sums[cat] += value

Now as far as I can tell, I'm not trying to iterate over an integer. I'm trying to add a value to another value inside catnums.

Is it possible that it is having trouble with the "cats" argument inside my accumulate_by_category() function?


回答1:


Each of your values is a list. The + operator, when applied to lists adds an iterable to a list. It doesn't append a single value:

>>> [1,2] + [3,4]
[1, 2, 3, 4]
>>> [1,2] + 3
TypeError: can only concatenate list (not "int") to list

It looks like you want to do cat_sums[cat].append(value).




回答2:


+, when applied to lists, is concatenation. As BrenBarn said, [1, 2] + [3, 4] == [1, 2, 3, 4].

But if you are actually trying to add numbers, as implied by your statement "I'm trying to add a value to another value inside catnums," then append will not do what you want.

If this is the case then the dictionary you show is probably incorrect. It's not a mapping of words to numbers; it's a mapping of words to lists of numbers (namely the list [0]). If you're trying to maintain a count of words, this is not what you want; you want {'composed': 0, 'elated': 0, ...} (note the lack of square brackets). Then the += statement will work as expected.

If you cannot change the dictionary but simply want to change the number in the list, you can say cat_sums[cat][0] += value. However, it would make far more sense (if this is what you're after) to simply convert the "lists of zero" into plain old zeroes.




回答3:


If anyone is getting this error inside a Django template …

When you do:

{% for c in cat_sums.keys %}

then, behind the scenes, the Django template language first tries a cat_sums['keys'] lookup. Normally this would fail and Django would next look for a method. But since this is a defaultdict, the default value gets stored instead.

If the dict was created with

cat_sums = defaultdict(int)

What gets executed is:

for c in cat_sums['keys']:

i.e.,

for c in 0:

which quite rightly throws an error as the value 0 is not iterable.

Resolution? Pass dict(cat_sums) inside the context so the view gets a regular dict.



来源:https://stackoverflow.com/questions/11533650/getting-int-object-is-not-iterable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!