我有3个numpy数组:
a = numpy.array([['x','y']])
b = numpy.array([['x1','y1']])
c = numpy.array([['x2','y2']])
我想创建一个字典:
d={'x': ['x1','x2'], 'y':['y1','y2']}
如何创建这样的字典?
答案 0 :(得分:3)
zip
字典理解中的数组:
d = {x: list(*i) for x, i in zip(*a, (b, c))}
或者,或者:
d = {x: [y, z] for x, (y, z) in zip(*a, (*b, *c))}
或者,如果您喜欢深度解包方案:
d = {x: [y, z] for x, ((y, z),) in zip(*a, (b, c))}
有很多包装/拆包组合可供选择。所有这些当然产生相同的输出,字典d
现在是:
{'x': ['x1', 'y1'], 'y': ['x2', 'y2']}
答案 1 :(得分:3)
如果你真的想要d={'x':['x1','x2'],'y':['y1','y2']}
,你可以去:
d = {i: [j, x] for i,j,x in zip(a,b,c)}
答案 2 :(得分:1)
如果要保留数组:
print {k: a for k, a in zip(a[0], [b, c])}
>>> {'y': array([['x2', 'y2']],
dtype='|S2'), 'x': array([['x1', 'y1']],
dtype='|S2')}
否则:
print {k: list(a[0]) for k, a in zip(a[0], [b, c])}
>>> {'y': ['x2', 'y2'], 'x': ['x1', 'y1']}
答案 3 :(得分:1)
以下是numpy
解决方案:
import numpy as np
dict(zip(np.ravel(a), np.vstack([b, c]).tolist()))
#{'x': ['x1', 'y1'], 'y': ['x2', 'y2']}
答案 4 :(得分:0)
您可以尝试这样的事情:
d = {k:list(v) for k,v in zip(a,(b,c))}
print(d)
输出:
{'x': ['x1', 'y1'], 'y': ['x2', 'y2']}