我怎樣才能設定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]
}
uj5u.com熱心網友回復:
使用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]}
>>>
uj5u.com熱心網友回復:
您可以簡單地使用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]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347795.html
上一篇:字典明智的減法
