【发布时间】:2020-05-19 20:35:09
【问题描述】:
有两个列表:
customer_list = ["A7", "A8", "A9", "A10", "A11"]
customer_index = ["8", "9", "10", "11", "12"]
目标是创建以下内容:
final_list = [
{
"kind": "report#variable",
"type": "A7",
"value": line[8]}
,
{
"kind": "report#variable",
"type": "A8",
"value": line[9]}
,
{
"kind": "report#variable",
"type": "A9",
"value": line[10]}
,
{
"kind": "report#variable",
"type": "A10",
"value": line[11]}
,
{
"kind": "report#variable",
"type": "A11",
"value": line[12]}
]
我尝试使用以下 Python 代码,但没有成功:
def create_final_list(list_1, list_2):
new_list = []
list_prefix = '{"kind": "report#variable",'
for num in list_1:
for val in list_2:
list_1_num = ' "type": ' + num
list_2_val = ' "value": ' + val
new_list.append(list_prefix + list_1_num + list_2_val)
return new_list
如上例所示,如何根据两个等长和所需格式的列表自动创建字典列表?
【问题讨论】:
-
您不是在创建 JSON,而是在创建一个 dict 对象列表。
-
不要尝试手动构造 JSON 字符串。先构造实际的对象(列表或字典),然后让Python内置的
json模块生成字符串。 -
您使用的是 Python 2 还是 Python 3? 它不起作用究竟是什么意思?
标签: python python-3.x pandas list python-2.7