gpt4 book ai didi

python - python中Json格式的两个列表

转载 作者:太空狗 更新时间:2023-10-29 20:12:29 27 4
gpt4 key购买 nike

我有两个列表

a=["USA","France","Italy"]
b=["10","5","6"]

我希望最终结果像这样在 json 中。

[{"country":"USA","wins":"10"},
{"country":"France","wins":"5"},
{"country":"Italy","wins":"6"},
]

我用 zip(a,b) 连接了两个但不能命名

最佳答案

使用 list comprehension :

>>> [{'country': country, 'wins': wins} for country, wins in zip(a, b)]
[{'country': 'USA', 'wins': '10'},
{'country': 'France', 'wins': '5'},
{'country': 'Italy', 'wins': '6'}]

使用json.dumps获取 JSON:

>>> json.dumps(
... [{'country': country, 'wins': wins} for country, wins in zip(a, b)]
... )
'[{"country": "USA", "wins": "10"}, {"country": "France", "wins": "5"}, {"country": "Italy", "wins": "6"}]'

关于python - python中Json格式的两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25348640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com