将 python 嵌套循环的结果存储到字典中

sta*_*d_0 5 python dictionary nested-loops

在做一些编码练习时,我遇到了这个问题:

“编写一个函数,接受带有键和整数列表的字典列表,并返回带有每个列表的标准差的字典。”

例如

input = [
    
    { 
        'key': 'list1',
        'values': [4,5,2,3,4,5,2,3]
        },

    {
        'key': 'list2',
        'values': [1,1,34,12,40,3,9,7],
    }
]
Run Code Online (Sandbox Code Playgroud)

回答:Answer: {'list1': 1.12, 'list2':14.19}

请注意,“值”实际上是值列表的键,一开始有点欺骗!

我的尝试:

def stdv(x):
    
    for i in range(len(x)):
        
        for k,v in x[i].items():
            result = {}
            print(result)
        
            if k == 'values':
                mean = sum(v)/len(v)                
                variance = sum([(j - mean)**2 for j in v]) / len(v)        
                
                stdv = variance**0.5
                
                return stdv   # not sure here!!
            
            result = {k, v} # this is where i get stuck
Run Code Online (Sandbox Code Playgroud)

我能够计算标准差,但我不知道如何按照答案中的建议将结果放回字典中。任何人都可以阐明它吗?非常感激!

小智 1

尝试以下操作,请注意,它不会将值添加到字典数组中。相反,它返回一个新的字典(如“答案:”所示),其中每个键都是来自key字典数组的...:

def stdv(x):
  ret = {}
  for i in range(len(x)):
    v = x[i]['values']
    mean = sum(v)/len(v)
    variance = sum([(j - mean)**2 for j in v]) / len(v)        
    ret[x[i]['key']] = variance**0.5
  return ret  
Run Code Online (Sandbox Code Playgroud)