我有一本字典
maketh = {'n':['1', '2', '3'], 'g': ['0', '5', '6', '9'], 'ca': ['4', '8', '1', '5', '9', '0']}
我打算改成
maketh_new = {'n':[1, 2, 3], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}
數字在值中的順序非常重要。因此,即使更改后,順序也應保持不變。
當我嘗試使用任何在線可用的方法進行更改時,我總是遇到的錯誤是:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
“如果有任何打字錯誤請忽略它......”
我根據自己的想法寫的一篇可能像這樣可以作業的是:
maketh_new = dict()
for (key, values) in maketh.items():
for find in len(values):
maketh_new [key] = int(values[find])
我試了一下,如果我可以將串列中值的所有元素作為字串訪問,那么我可以將 caste 輸入 int。但我得到一個錯誤:
'list' object cannot be interpreted as an integer
因此,如果有人可以幫助我找到解決方案,請執行...
uj5u.com熱心網友回復:
假設值中的所有元素都是數字,您可以map int對值:
maketh_new = {k: list(map(int, v)) for k, v in maketh.items()}
輸出:
{'n': [1, 2, 3], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}
如果沒有,您可以使用str.isdigit更安全的輸入:
maketh = {'n':['1', '2', 'a'], # Note 'a' at last
'g': ['0', '5', '6', '9'],
'ca': ['4', '8', '1', '5', '9', '0']}
maketh_new = {k: [int(i) if i.isdigit() else i for i in v] for k, v in maketh.items()}
輸出:
{'n': [1, 2, 'a'], 'g': [0, 5, 6, 9], 'ca': [4, 8, 1, 5, 9, 0]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447776.html
上一篇:從資料框中的字典中提取資訊
下一篇:從字典中獲取值
