You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python嵌套列表转换为包含字典元素的列表

实现思路
  • 先定义和bigList四个子列表顺序一一对应的字段名列表keys = ['name', 'stars', 'numrevs', 'price']
  • 按餐厅索引遍历,每次取出四个子列表对应索引的属性值,和字段名配对生成单家餐厅的字典
  • 将所有餐厅字典依次存入结果列表即可完成转换
代码实现

简洁版(列表推导式)

利用zip(*bigList)将原嵌套列表按列拆分,每一列恰好对应单家餐厅的四个属性:

bigList = [
    ['Gus’s World Famous Fried Chicken', 'South City Kitchen - Midtown', 'Mary Mac’s Tea Room', 'Busy Bee Cafe', 'Richards’ Southern Fried', 'Greens & Gravy', 'Colonnade Restaurant', 'South City Kitchen Buckhead', 'Poor Calvin’s', 'Rock’s Chicken & Fries', 'Copeland’s'],
    ['4.0', '4.5', '4.0', '4.0', '4.0', '3.5', '4.0', '4.5', '4.5', '4.0', '3.5'],
    [549, 1777, 2241, 481, 108, 93, 350, 248, 1558, 67, 288],
    ['$$', '$$', '$$', '$$', '$$', '$$', '$$', '$$', '$$', '$', '$$']
]
keys = ['name', 'stars', 'numrevs', 'price']
restaurant_list = [dict(zip(keys, values)) for values in zip(*bigList)]

易读版(普通循环)

逻辑直观,适合新手理解:

restaurant_list = []
keys = ['name', 'stars', 'numrevs', 'price']
# 遍历所有餐厅的索引
for i in range(len(bigList[0])):
    rest_dict = {
        'name': bigList[0][i],
        'stars': bigList[1][i],
        'numrevs': bigList[2][i],
        'price': bigList[3][i]
    }
    restaurant_list.append(rest_dict)

调用restaurant_list[0]['name']即可得到第一家餐厅名称Gus’s World Famous Fried Chicken,完全符合要求。

内容的提问来源于stack exchange,提问作者PDubs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:48:04