print(type(directreceipts))
print(directreceipts)
o/p
1
2
<class 'list'>
['{\n "quantityOfUnits": 1500,\n "ownerOnDespatch": "100038",\n "packSize": 3\n}', '{\n "quantityOfUnits": 2500,\n "ownerOnDespatch": "100038",\n "packSize": 4\n}']
想要將字串串列轉換為字典并訪問值,并且還想要消除 \n。
uj5u.com熱心網友回復:
您無需嘗試在\n此處洗掉。只需用json.
import json
directreceipts = [json.loads(d) for d in directreceipts]
輸出:
[{'quantityOfUnits': 1500, 'ownerOnDespatch': '100038', 'packSize': 3},
{'quantityOfUnits': 2500, 'ownerOnDespatch': '100038', 'packSize': 4}]
您可以訪問這些值,例如,
單值訪問,
In [1]: directreceipts[0]['quantityOfUnits']
Out[1]: 1500
理想情況下,遍歷并訪問這些值
In [2]: for item in directreceipts:
...: print(item['quantityOfUnits'])
...:
1500
2500
要找到這些值的總和,請使用串列推導。
In [3]: sum([item['quantityOfUnits'] for item in directreceipts])
Out[3]: 4000
uj5u.com熱心網友回復:
嘗試這個
list_object[0].encode("utf-8").decode()
或者你也可以試試這個:
import json
json.loads(list_object[0])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/516742.html
