python - 如何通过字典或JSON等似是而非的格式将三个列表合并为一个列表? Python

标签 python json list dictionary

我有三个列表:

imglist=['1.jpg', '12.jpg']
classlist=['class1', 'class5']
sentencelist=['Good for health.', 'Good luck.']

如何将列表组合成如下格式?

[ ['1.jpg','class1','Good for health.'],
['12.jpg','class5','Good luck.']]

或者您是否知道如何将列表合并为字典或 JSON 格式?比如

[{'img':'1.jpg','class':'class1','sentence':'Good for health.'},
{'img':'12.jpg','class':'class5','sentence':'Good luck'}]

最佳答案

使用zip()将列表合并为:

>>> imglist=['1.jpg', '12.jpg']
>>> classlist=['class1', 'class5']
>>> sentencelist=['Good for health.', 'Good luck.']

# combining list
>>> zip(imglist, classlist, sentencelist)
[('1.jpg', 'class1', 'Good for health.'), ('12.jpg', 'class5', 'Good luck.')]

要将其转换为您格式的 dict,请使用 ziplist comprehension 作为:

>>> key_list = ["img", "class", "sentence"]
>>> my_zipped_list = zip(imglist, classlist, sentencelist)  # same list as above example

>>> [dict(zip(key_list, zipped_element)) for zipped_element in my_zipped_list]
[{'class': 'class1', 'img': '1.jpg',  'sentence': 'Good for health.'},
 {'class': 'class5', 'img': '12.jpg', 'sentence': 'Good luck.'}]

关于python - 如何通过字典或JSON等似是而非的格式将三个列表合并为一个列表? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40503037/

相关文章:

python - 使用pyclutter编程

python - matplotlib 两个传说出情节

python - 程序员说 "raise an error"是什么意思(例如,为什么要这样做)?

Python字典单键可以有多个值吗?

python - 根据每个组的第一个元素从列表列表中收集元素

python - 从实例而不是类继承 [Python 3]

javascript - Json,显示用户名

c# - 模型绑定(bind)和继承 ASP MVC 5

Java JSON - 覆盖 @JsonIgnore 进行测试

php - 如何用逗号分隔数组的值以供显示