【问题标题】:Adding 1 to Value in Dictionary字典中的值加 1
【发布时间】:2016-07-15 04:02:45
【问题描述】:

我见过其他将字典中的值加 1 的方法。 当我尝试将值 1 添加到 python 中的字典键值时,我只是不断收到错误。

这是我的代码:

arr = {('1', '20'): [0], ('15', '14'): [0]}

我想给键加 1 ('1', '20')。

这是我的代码:

w = 1
x = 20
arr[(w, x)] += 1

我得到错误代码:

TypeError: 'int' object is not iterable

我根本不知道我做错了什么。非常感谢任何建议。

【问题讨论】:

    标签: python dictionary key updates key-value


    【解决方案1】:

    两个问题:

    1. 字典的键是字符串元组,但您尝试使用整数元组对字典进行索引。
    2. 您的字典中的值是(1 长度)整数列表,但您正试图向其中一个列表添加一个数字。

    你可能想要这样的东西:

    w = '1'
    x = '20'
    arr[(w, x)][0] += 1
    

    如果没有看到更多代码,您可能想要更多类似的东西:

    # dictionary mapping tuples of ints to ints
    arr = { (1, 20): 0, (15, 14): 0 }
    
    # now we can just use ints    
    w = 1
    x = 20
    # and no need to use [0] to get the first element of the list
    # (because it's no longer a list)
    arr[(w, x)] += 1
    

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      相关资源
      最近更新 更多