[英]Python Dictionary contains List as Value - How to update based on some other input
[英]Python Dictionary contains List as Value - How to update?
我有一个字典作为列表有价值。
dictionary = {
'C1' : [10,20,30]
'C2' : [20,30,40]
}
假设我想将C1列表中的所有值递增10,我该怎么做?
dictionary.get('C1')
给我列表,但我如何更新它?
>>> 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]}
访问的字典值(在这种情况下为列表)是原始值,与用于访问它的字典分开。 无论是否在字典中,您都会以相同的方式递增列表中的值:
l = dictionary.get('C1')
for i in range(len(l)):
l[i] += 10
dictionary["C1"]=map(lambda x:x+10,dictionary["C1"])
应该这样做......
为什么不跳过.get完全做这样的事情?:
for x in range(len(dictionary["C1"]))
dictionary["C1"][x] += 10
可能是这样的:
original_list = dictionary.get('C1')
new_list = []
for item in original_list:
new_list.append(item+10)
dictionary['C1'] = new_list
for i,j in dictionary .items():
if i=='C1':
c=[]
for k in j:
j=k+10
c.append(j)
dictionary .update({i:c})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.