例如,这是我的输入矩阵
a = [['1', '2', '3', '4', '5', '6'],['1', '2', '3', '4', '5', '6'],['1',
'2', '3', '4', '5', '6']]
b = [[(1, 0.044), (2, 0.042)], [(4, 0.18), (6, 0.023)], [(4, 0.03), (5,
0.023)]]
我想得到
c= [[0.044, 0.042, 0, 0, 0, 0][0, 0, 0, 0.18, 0, 0.023][0, 0, 0, 0.03,0.023,
0]]
如果b [0]中的第一个值== a [0],则将矩阵a [0]与b [0]合并,然后用b中的第二个值替换a中的值,依此类推。
我尝试这样编码:
bnn = dict(chain.from_iterable(b))
for i in a:
for ii in i:
c = [bnn.get(i, 0) for i in map(int, ii)]
print(c)
但它显示了:
[0.044]
[0.042]
[0]
[0.03]
[0.023]
[0.023]
[0.044]
[0.042]
[0]
[0.03]
[0.023]
[0.023]
[0.044]
[0.042]
[0]
[0.03]
[0.023]
[0.023]
我应该如何编码?
答案 0 :(得分:0)
一种方法是将map
,列表理解和字典与get
一起使用:
c = []
for n, i in enumerate(a):
c.append([dict(b[n]).get(i, 0) for i in map(int, a[n])])
c
输出:
[[0.044, 0.042, 0, 0, 0, 0],
[0, 0, 0, 0.18, 0, 0.023],
[0, 0, 0, 0.03, 0.023, 0]]
答案 1 :(得分:0)
一种使用广播的numpy
解决方案,假设a
仅用于“显示”场所。
key,val = np.array(b).T
key = key.astype(int)-1 # -1 because in Python first place is at index 0.
res = zeros_like(a,dtype=val.dtype)
res[range(len(a)),key] = val
输出:
[[ 0.044 0.042 0. 0. 0. 0. ]
[ 0. 0. 0. 0.18 0. 0.023]
[ 0. 0. 0. 0.03 0.023 0. ]]