Python 字典包含列表作为值 - 如何更新?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4527454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:07:47  来源:igfitidea点击:

Python Dictionary contains List as Value - How to update?

pythonlistdictionary

提问by Deepak

I have a dictionary which has value as a list.

我有一本字典,它具有列表的价值。

dictionary = { 
               'C1' : [10,20,30] 
               'C2' : [20,30,40]
             }

Let's say I want to increment all the values in list of C1 by 10, how do I do it?

假设我想将 C1 列表中的所有值增加 10,我该怎么做?

dictionary.get('C1')gives me the list but how do i update it?

dictionary.get('C1')给了我列表,但我如何更新它?

采纳答案by Paolo Bergantino

>>> dictionary = {'C1' : [10,20,30],'C2' : [20,30,40]}
>>> dictionary['C1'] = [x+1 for x in dictionary['C1']]
>>> dictionary
{'C2': [20, 30, 40], 'C1': [11, 21, 31]}

回答by girasquid

Probably something like this:

大概是这样的:

original_list = dictionary.get('C1')
new_list = []
for item in original_list:
  new_list.append(item+10)
dictionary['C1'] = new_list

回答by Utku Zihnioglu

dictionary["C1"]=map(lambda x:x+10,dictionary["C1"]) 

Should do it...

应该这样做...

回答by Gabe

An accessed dictionary value (a list in this case) is the original value, separate from the dictionary which is used to access it. You would increment the values in the list the same way whether it's in a dictionary or not:

访问的字典值(在本例中为列表)是原始值,与用于访问它的字典分开。无论是否在字典中,您都可以以相同的方式增加列表中的值:

l = dictionary.get('C1')
for i in range(len(l)):
    l[i] += 10

回答by user5261053

why not just skip .get altogether and do something like this?:

为什么不完全跳过 .get 并做这样的事情?:

for x in range(len(dictionary["C1"]))
    dictionary["C1"][x] += 10

回答by Loki

for i,j in dictionary .items():
    if i=='C1':
        c=[]
        for k in j:
            j=k+10
            c.append(j)
            dictionary .update({i:c})