字典格式的Json文件数据

问题描述 投票:0回答:1

我有一个json文件,其中的数据格式是:[{"数据":最大资本损失:2000.0}] [{"数据":最大资本利润:10.0}][{"数据":交易次数:20.0}]]。[{"数据":最大资本损失:2000.0}] [{"数据":最大资本利润:10.0}][{"数据":交易次数:20.0}] ] 。

现在我想要这样的数据[{"数据":最大资本损失:2000.0}, {"数据":最大资本利润:10.0}, {"数据":交易次数:20.0}] 。我想删除列表中的逗号,但整个字典数据到一个列表中。

python-3.x
1个回答
0
投票

假设你的数据确实是上面的格式,你可以在Python中使用嵌套列表理解法将列表扁平化为一个单一的列表。

>>> import json

# load json from string (use json.load(path) to load from file)
>>> data = json.loads("""
[
[{"data": {"max capital loss": 2000.0}}], 
[{"data": {"max capital profit": 10.0}} ],
[{"data": {"no of trades": 20.0}}]
]
""")

# flatten the list
>>> flattened_data = [item for lst in data for item in lst]

# output
>>> print(flattened_data)
[{'data': {'max capital loss': 2000.0}},
 {'data': {'max capital profit': 10.0}},
 {'data': {'no of trades': 20.0}}]
© www.soinside.com 2019 - 2024. All rights reserved.