【问题标题】:Editing each element within the lists within the values of a dictionary (Python)在字典的值中编辑列表中的每个元素(Python)
【发布时间】:2020-08-13 14:07:22
【问题描述】:

这是我抓取字典的尝试:

pairs = {'EMOTIONS': ['happy', 'angry', 'sad', 'calm'], 'TRAITS': ['impatient', 'persistent', 'meek']}

然后把它变成一个字典,它的值被写成一个短语,所以:

pairs = {'EMOTIONS': ['I am happy', 'I am angry', 'I am sad', 'I am calm'], 'TRAITS': ['I am impatient', 'I am persistent', 'I am stubborn']} 

这是目前为止的代码:

pairs = {'EMOTIONS': ['happy', 'angry', 'sad', 'calm'], 'TRAITS': ['impatient', 'persistent', 'meek']}
I_am = 'I am '

for title, words in pairs.items():
    words = [I_am+word for word in words]

我显然做错了,因为当我请求 print(pairs) 时,它返回的字典与我开始时完全相同。我要进行哪些更改才能完成这项工作?

【问题讨论】:

    标签: python list loops dictionary list-comprehension


    【解决方案1】:

    确保改变列表,而不仅仅是重新绑定循环变量:

    for words in pairs.values():
        words[:] = [I_am + word for word in words]
        # or, if you want to be fancy
        words[:] = map(I_am.__add__, words)
    

    这使用slice assignment 来更改list 对象。

    【讨论】:

      【解决方案2】:

      当你说

          words = [I_am+word for word in words]
      

      您使用您正在寻找的前缀创建一个新列表,并将该列表分配给局部变量words,但您不会以任何方式更改字典的值。为此,这应该有效:

      new_pairs = {key: [I_am + adjective for adjective in pairs[key]] for key in pairs}
      

      【讨论】:

        【解决方案3】:

        使用单个 for 循环。

            pairs = {'EMOTIONS': ['happy', 'angry', 'sad', 'calm'], 'TRAITS': ['impatient', 'persistent', 'meek']}
            dic = {}
            for x,y in pairs.items():dic[x]=list(map(lambda x:'I am '+x,y))
            print(dic)
        

        【讨论】:

          【解决方案4】:

          尝试创建一个新字典并在 for 循环中写入:

          modpairs = {}
          for title, words in pairs.items():
              words = [I_am+word for word in words]
              modpairs[title] = words
          print(modpairs)
          

          【讨论】:

          • 您可以就地修改 pairs 中的值,但在迭代字典项时修改字典并不是一个好的常规做法。
          猜你喜欢
          • 2023-03-20
          • 2011-03-06
          • 2014-04-14
          • 1970-01-01
          • 1970-01-01
          • 2021-07-16
          • 1970-01-01
          • 2019-11-24
          • 2012-12-13
          相关资源
          最近更新 更多