Getting 'int' object is not iterable

后端 未结 3 696
慢半拍i
慢半拍i 2021-01-25 20:37
    cat_sums[cat] += value
TypeError: \'int\' object is not iterable

My input is this:

defaultdict(, {\'composed\'         


        
3条回答
  •  旧时难觅i
    2021-01-25 21:13

    +, 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.

提交回复
热议问题