平均字典的内部列表

时间:2018-01-02 16:37:35

标签: python python-2.7

假设我有以下词典:

dict_ = {0: {40: [0.692, 0.76, 0.01]}, 1: {33: [0.69, 0.02]}, 2: {39: [0.698, 0.023]}}

我想将内部列表平均在一起,以便生成最终的平均列表,如下所示:[(0.692+0.690.698)/3, (0.76+0.02+0.023)/3, (0.01+0.0+0.0)/3]。我的以下代码是:

for i in dict_:
    for j in dict_[i]:
        W = [sum(e) / len(e) for e in zip(*dict_[i][j])]
print(W)

有这个错误:

Traceback (most recent call last):
  File "test.py", line 97, in <module>
    W = [sum(e) / len(e) for e in zip(* dict_[i][j])]
TypeError: zip argument #1 must support iteration

我该如何解决?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:7)

你可以试试这个:

dict_ = {0: {40: [0.692, 0.76, 0.01]}, 1: {33: [0.69, 0.02]}, 2: {39: [0.698, 0.023]}}
inner_sum = [[sum(c)/float(len(c)) for d, c in b.items()][0] for a, b in dict_.items()]

编辑:您似乎正在尝试压缩内部列表,如果每个列表的长度不相同,请将期望值替换为0:

import itertools
final_data = [[0 if b is None else b for b in i] for i in itertools.izip_longest(*[b.values() for a, b in dict_.items()])][0]
print(final_data)
averages = [sum(i)/float(len(i)) for i in final_data]
print(averages)

输出:

[[0.692, 0.69, 0.698], [0.76, 0.02, 0.023], [0.01, 0, 0]]
[0.6933333333333334, 0.26766666666666666, 0.0033333333333333335]

对于Python3,请改用zip_longest

final_data = [[0 if b is None else b for b in i] for i in itertools.zip_longest(*[b.values() for a, b in dict_.items()])]

答案 1 :(得分:1)

我玩得很开心,然后把它变成了一个oneliner。

不要在生产代码中使用它!

d = {0: {40: [0.692, 0.76, 0.01]}, 1: {33: [0.69, 0.02]}, 2: {39: [0.698, 0.023]}}

print(map(lambda L: sum(L)/len(L),map(lambda L:map(lambda v:float(v or 0),L),map(None,*[L for nd in d.values() for L in nd.values()]))))

其中:

d: your dict
nd: nested dict in d
L: a list
v: an element (in the list L)