字典列表中的计算

2024-06-28 20:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典清单:

wt
Out[189]: 
[defaultdict(int,
             {'A01': 0.15,
              'A02': 0.17,
              'A03': 0.13,
              'A04': 0.17,
              'A05': 0.01,
              'A06': 0.12,
              'A07': 0.15,
              'A08': 0.0,
              'A09': 0.02,
              'A10': 0.09}),
 defaultdict(int,
             {'A01': 0.02,
              'A02': 0.02,
              'A03': 0.06,
              'A04': 0.08,
              'A05': 0.08,
              'A06': 0.04,
              'A07': 0.02,
              'A08': 0.24,
              'A09': 0.34,
              'A10': 0.1}),
 defaultdict(int,
             {'A01': 0.0,
              'A02': 0.12,
              'A03': 0.01,
              'A04': 0.01,
              'A05': 0.11,
              'A06': 0.13,
              'A07': 0.1,
              'A08': 0.36,
              'A09': 0.13,
              'A10': 0.03})]

我还有一本字典:

zz
Out[188]: defaultdict(int, {'S1': 0.44, 'S2': 0.44, 'S3': 0.12})

我需要运行一个循环来聚合以下计算:

'S1':0.44 * 'A01':0.15 + 'S2':0.44 * 'A01':0.02 + 'S3':0.12 * 'A01':0.00 ----- to be stored in a dict with the key 'A01'
'S1':0.44 * 'A02':0.17 + 'S2':0.44 * 'A02':0.02 + 'S3':0.12 * 'A02':0.12 ----- to be stored in a dict with the key 'A02'
.
.
.and so on upto:
'S1':0.44 * 'A10':0.09 + 'S2':0.44 * 'A10':0.1 + 'S3':0.12 * 'A10':0.03 ----- to be stored in a dict with the key 'A10'

谁能给我个建议吗?我面临的问题是:

wt[0]
Out[197]: 
defaultdict(int,
            {'A01': 0.15,
             'A02': 0.17,
             'A03': 0.13,
             'A04': 0.17,
             'A05': 0.01,
             'A06': 0.12,
             'A07': 0.15,
             'A08': 0.0,
             'A09': 0.02,
             'A10': 0.09})

但是:

wt[0][0]
Out[199]: 0

我无法访问dict中的每个值


Tags: outa10ints2s1defaultdicta01a02
1条回答
网友
1楼 · 发布于 2024-06-28 20:19:55

你可以通过听写理解进行聚合:

x = [defaultdict(int, {'A01': 0.15, 'A02': 0.17, 'A03': 0.13, 'A04': 0.17, 'A05': 0.01, 'A06': 0.12, 'A07': 0.15, 'A08': 0.0, 'A09': 0.02, 'A10': 0.09}), 
     defaultdict(int, {'A01': 0.02, 'A02': 0.02, 'A03': 0.06, 'A04': 0.08, 'A05': 0.08, 'A06': 0.04, 'A07': 0.02, 'A08': 0.24, 'A09': 0.34, 'A10': 0.1}), 
     defaultdict(int, {'A01': 0.0, 'A02': 0.12, 'A03': 0.01, 'A04': 0.01, 'A05': 0.11, 'A06': 0.13, 'A07': 0.1, 'A08': 0.36, 'A09': 0.13, 'A10': 0.03})]
mult = defaultdict(int, {'S1': 0.44, 'S2': 0.44, 'S3': 0.12})

d = {k: sum(d[k] * mult['S'+str(idx+1)] 
     for idx, d in enumerate(x)) for k in x[0].keys()}

如果要将矩阵与向量相乘,应尝试numpy:

import numpy as np

# Transform data to matrix
x = np.array([[d['A'+str(i+1).zfill(2)] for i in range(len(d))] for d in x])
v = np.array([mult['S'+str(i+1)] for i in range(len(mult))]).reshape(1, 3)

print(np.matmul(v, x))
# [[0.0748 0.098  0.0848 0.1112 0.0528 0.086  0.0868 0.1488 0.174  0.0872]]

相关问题 更多 >