在字典python列表中求和键和值

时间:2017-10-06 00:21:44

标签: python dictionary key

我有一个名为" timebucket"的词典列表。 :

[{0.9711533363722904: 0.008296776727415599}, 
 {0.97163564816067838: 0.008153794130319884}, 
 {0.99212783984967068: 0.0022392112909864364}, 
 {0.98955473263127025: 0.0029843621053514003}]

我想返回前两个最大的键(.99和.98)并对它们取平均值,另外,得到它们的两个值并平均值。

预期输出类似于:

 { (avg. two largest keys) : (avg. values of two largest keys) }

我试过了:

import numpy as np
import heapq
[np.mean(heapq.nlargest(2, i.keys())) for i in timebucket]

但是heapq在这种情况下不起作用,并且不确定如何保持键和值的链接

5 个答案:

答案 0 :(得分:0)

使用public function purchases() { return $this->hasMany(Purchases::class); }

执行此操作
numpy

虽然我怀疑预先创建一个更好的数据结构可能是一种更好的方法。

答案 1 :(得分:0)

这为您提供了2个最大键(keyave)的平均值和两个相应值(valave)的平均值。 键和值被放入一个名为newdict的字典中。

timebucket = [{0.9711533363722904: 0.008296776727415599}, 
 {0.97163564816067838: 0.008153794130319884}, 
 {0.99212783984967068: 0.0022392112909864364}, 
 {0.98955473263127025: 0.0029843621053514003}]
keys = []
for time in timebucket:
  for x in time:
    keys.append(x)
result = {}
for d in timebucket:
   result.update(d)


largestkey = (sorted(keys)[-1])
ndlargestkey = (sorted(keys)[-2])
keyave = (float((largestkey)+(ndlargestkey))/2)

largestvalue = (result[(largestkey)])
ndlargestvalue = (result[(ndlargestkey)])
valave = (float((largestvalue)+(ndlargestvalue))/2)
newdict = {}
newdict[keyave] = valave

print(newdict)
#print(keyave)
#print(valave)

输出 {0.9908412862404705: 0.002611786698168918}

答案 2 :(得分:0)

以下是您问题的解决方案:

/Games

我希望它有所帮助

答案 3 :(得分:0)

你只需要四行即可完成,而无需导入numpy:

  

一线解决方案

     

两个最大平均密钥:

max_keys_average=sorted([keys for item in timebucket for keys,values in item.items()])[::-1][:2]


print(sum(max_keys_average)/len(max_keys_average))

输出:

0.9908412862404705
  

他们的平均密钥:

max_values_average=[values for item in max_keys_average for item_1 in timebucket for keys,values in item_1.items() if item==keys]

print(sum(max_values_average)/len(max_values_average))

输出:

0.002611786698168918
  

如果您面临理解列表理解的问题,这里有详细的解决方案:

     

详细解决方案

第一步:

在一个列表中获取dict的所有键:

Here is your timebucket list:

timebucket=[{0.9711533363722904: 0.008296776727415599},
 {0.97163564816067838: 0.008153794130319884},
 {0.99212783984967068: 0.0022392112909864364},
 {0.98955473263127025: 0.0029843621053514003}]

现在让我们将所有密钥存储在一个列表中:

keys_list=[]

for dict in timebucket:
    for key,value in dict.items():
        keys_list.append(key)

现在,下一步是对此列表进行排序,并获取此列表的最后两个值:

max_keys=sorted(keys_list)[::-1][:2]

下一步只需获取此新列表的总和并除以列表列表:

print(sum(max_keys)/len(max_keys))

输出:

0.9908412862404705

现在只需迭代timebucket中的max_keys和键,看看两个项是否匹配,然后在列表中获取该项的值。

max_values=[]

for item in max_keys:
    for dict in timebucket:
        for key, value in dict.items():
            if item==key:
                max_values.append(value)

print(max_values)

现在最后一部分,只需要求和除以max_values的len:

print(sum(max_values)/len(max_values))

给出输出:

0.002611786698168918

答案 4 :(得分:0)

这是解决问题的另一种方法:

In []:
import numpy as np
import time

def AverageTB(time_bucket):
    tuples = [tb.items() for tb in time_bucket]
    largest_keys = []
    largest_keys.append(max(tuples))
    tuples.remove(max(tuples))
    largest_keys.append(max(tuples))
    keys = [i[0][0] for i in largest_keys]
    values = [i[0][1] for i in largest_keys]
    return np.average(keys), np.average(values)

time_bucket = [{0.9711533363722904: 0.008296776727415599},
           {0.97163564816067838: 0.008153794130319884},
           {0.99212783984967068: 0.0022392112909864364},
           {0.98955473263127025: 0.0029843621053514003}]
time_exe = time.time()
print('avg. (keys, values): {}'.format(AverageTB(time_bucket)))
print('time: {}'.format(time.time() - time_exe))


Out[]:
avg. (keys, values): (0.99084128624047052, 0.0026117866981689181)
time: 0.00037789344787