【问题标题】:How can I change the value of an element in a list which belongs to a dictionary?如何更改列表中属于字典的元素的值?
【发布时间】:2019-04-05 17:37:35
【问题描述】:

我有一个元组字典作为键和列表的值称为 dictionary 如下所示,我只想更改列表中 67 元素的值。例如第二个元素属于键 (1,2,3) 的列表。我编写了以下代码,但我收到一条错误消息,提示“列表索引必须是整数或切片,而不是 str”。

dictionary = { (1,2,3) : [234,67],
               (2,2,3) : [4,7]
}


for i in dictionary:
    for j in i:
        if dictionary[i][j] == 67:
           dictionary[i][j] = 50

有人可以帮助我了解我做错了什么吗?我真的很绝望

【问题讨论】:

    标签: python list dictionary data-structures tuples


    【解决方案1】:

    == 用于比较; = 用于分配。但是,您在对待i 的方式上也存在错误。 i 是一个类似于(1,2,3) 的键,但您将它视为值dictionary[i]。如果要修改列表,还需要列表的索引,因此使用enumerate 会有所帮助。

    for i in dictionary:  # i is tuple like (1,2,3)
        # enumerate(dictionary[i]) yields a sequence of tuples
        # like (0, 234), (1, 67)
        for j, value in enumerate(dictionary[i]):
            if value == 67:
                dictionary[i][j] = 50
    

    就像enumerate 为您提供列表中的索引和值一样,您可以使用items 方法在迭代dict 时同时获取键和值。

    # list_value stands in for dictionary[i]
    for i, list_value in dictionary.items():
        for j, value in enumerate(list_value):
            if value == 67:
                list_value[j] = 50
    

    【讨论】:

      【解决方案2】:

      您的代码中有很多错误,但这应该可以:

      for i in dictionary:
          for j in range(len(dictionary[i])):
              if dictionary[i][j] == 67:
                  dictionary[i][j] = 50
      

      在您的代码中,for j in i 指的是字典键中的数字。这是无法更改的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多