基本上我想知道如何在python中將陣列轉換為字典。
import numpy as np
a=np.array(\[23,34,23,45,23\])
print(a)
輸出 [23 34 23 45 23]
但我想要
{0:"23",1:"34",2:"23",3:"45",4:"23"}
uj5u.com熱心網友回復:
似乎陣列中的值在添加到目標字典時需要轉換為字串。所以:
import numpy as np
a = np.array([23,34,23,45,23])
d = dict(enumerate(map(str, a)))
print(d)
輸出:
{0: '23', 1: '34', 2: '23', 3: '45', 4: '23'}
uj5u.com熱心網友回復:
通過 enumerate() 迭代并為 dict-members 使用 f 格式
mydict={}
for index, i in enumerate(a):
mydict[index]=f"{i}"
print(mydict)
f 格式: https ://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498
uj5u.com熱心網友回復:
您可以使用類似的理解
dic={i:a[i] for i in range(len(a))}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456016.html
標籤:Python 数组 python-3.x 字典
