python - Python从多个列表中创建字典列表
问题描述
如何将列表转入字典列表?
从:
name=['Mary','Susan','John']
age=[15,30,20]
sex=['F','F','M']
我希望有 :
mylist= [ {'name':'Mary','age':15,'sex':'F'},
{'name':'Susan','age':30,'sex':'F'},
{'name':'John','age':20,'sex':'M'},
]
解决方案
This is a perfect example of the zip
function. https://docs.python.org/3.8/library/functions.html#zip
Given:
name = ['Mary','Susan','John']
age = [15,30,20]
sex = ['F','F','M']
Then:
output = []
for item in zip(name, age, sex):
output.append({'name': item[0], 'age': item[1], 'sex': item[2]})
Will produce:
[
{'name': 'Mary', 'age': 15, 'sex': 'F'},
{'name': 'Susan', 'age': 30, 'sex': 'F'},
{'name': 'John', 'age': 20, 'sex': 'M'},
]
There is an even shorter way to do it with list comprehensions:
output = [{'name': t[0], 'age': t[1], 'sex': t[2]} for t in zip(name, age, sex)]
推荐阅读
- unity3d - Unity2D:当相机视图的末端位于 x=0 或 y=0 时,相机会导致奇怪的撕裂问题
- c# - 使用带有 linq 的 In 子句时无法从“字符串”转换为“字符串 []”
- ruby-on-rails - 在 Rails 生产应用程序的 cron 作业中,Rake 任务失败
- java - 日期比较给出错误输出
- prestashop - Prestashop 网络服务:无法使用自定义价格创建购物车
- python - 使用 Conv1D 层时出现 ValueError
- flutter - BlocProvider 中的惰性标志有什么影响?
- android - 如何从视图中获取 TextView 和 Button 列表
- automated-tests - 点击发送请求时出现 Cypress 400 XHR 错误
- javascript - 使用 formdata 启动 axios 发布请求时反应更新页面