使用循环创建带有两个列表的多个JSON文件
我想问如何用两个列表制作多个JSON文件? 假设我的输入是:
animal_list = ["cat", "dog", "bird", "fish", "chicken", "tiger"]
name_file = ["a", "b", "c", "d", "e", "f"]
我想要的输出是:
a.json -> "cat"
b.json -> "dog"
c.json -> "bird"
d.json -> "fish"
e.json -> "chicken"
f.json -> "tiger"
因此,文件a.json
包含“ cat”
,文件 b.json 包含<代码>“狗” 等。
I want to ask how to make multiple JSON files with two lists?
let's say my input is:
animal_list = ["cat", "dog", "bird", "fish", "chicken", "tiger"]
name_file = ["a", "b", "c", "d", "e", "f"]
and output that I want is:
a.json -> "cat"
b.json -> "dog"
c.json -> "bird"
d.json -> "fish"
e.json -> "chicken"
f.json -> "tiger"
so file a.json
contains "cat"
, file b.json
contains "dog"
etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下:
基本上,您是在缩放两个列表,然后在每次迭代中,您可以在字符串格式的帮助下打开一个新文件(您需要构建文件的名称),然后用
json.dump 方法。
也不要为变量使用内置名称。我故意将
列表
重命名为lst
。Try this:
Basically you are zipping your two lists, then in each iteration you open a new file with the help of string formatting(you need to build the file's name) then you dump your objects with
json.dump
method.Also do not use built-in names for your variable. I intentionally renamed
list
tolst
.您正在寻找
zip()
函数。它允许您同时迭代多个列表的元素。从那里,您可以使用F-string打开每个文件作为
.json
文件来创建文件名,然后写出内容。要写入JSON格式,Python具有内置的
JSON
软件包。这将确保您要保存的任何Python对象都被格式化为适当的JSON。我们将使用json.dump
函数,该函数将您的内容带入文件对象。You are looking for the
zip()
function. It allows you to iterate over the elements of multiple lists at the same time.From there you can open each file as a
.json
file using an f-string to create the file name, and then write out the contents.To write out to the JSON format, Python has the built-in
json
package. This will ensure whatever Python object you want to save is formatted as proper JSON. We will use thejson.dump
function, which takes your content and writes it to a file object.