格式化数组的值以适合字典

Formatting the values of an array to be fitted within a dictionary

如何将 numpy 数组 a 设置为字典 dictionary 中的三个列表集作为 one, two, three 就像下面的预期输出一样?

代码:

import numpy as np 
set_names = np.array(['one', 'two', 'three'])
a = np.array([12,4,2,45,6,7,2,4,5,6,12,4])
dictionary = {}

预期输出:

{
    'one': [12,4,2,45],
    'two': [6,7,2,4],
    'three': [5,6,12,4]
}

使用np.array_split:

>>> dict(zip(set_names, np.array_split(a, len(set_names))))
{'one': array([12,  4,  2, 45]), 'two': array([6, 7, 2, 4]), 'three': array([ 5,  6, 12,  4])}
>>> 

如列表:

>>> {k: list(v) for k, v in zip(set_names, np.array_split(a, len(set_names)))}
{'one': [12, 4, 2, 45], 'two': [6, 7, 2, 4], 'three': [5, 6, 12, 4]}
>>> 

您可以使用 reshape 简单地尝试这种方法。

import numpy as np

names = np.array(["one", "two", "three"])
a = np.array([12, 4, 2, 45, 6, 7, 2, 4, 5, 6, 12, 4])
dictionary = {}
for i, name in enumerate(names):
    dictionary[name] = list(a.reshape(len(names), -1)[i])

print(dictionary)

这给出了以下输出。

{'one': [12, 4, 2, 45], 'two': [6, 7, 2, 4], 'three': [5, 6, 12, 4]}

或者如果你想要一个单行的,这里是等效的字典理解。

print({name: list(a.reshape(len(names), -1)[i]) for i, name in enumerate(names)})

这给出了以下输出。

{'one': [12, 4, 2, 45], 'two': [6, 7, 2, 4], 'three': [5, 6, 12, 4]}