簡體   English   中英

如何從多個單獨的列表中創建字典列表?

[英]How can I create a list of dicts from multiple separate lists?

假設我有四個單獨的列表,如下所示:

colors = ['red', 'blue', 'green', 'black']
widths = [10.0, 12.0, 8.0, 22.0]
lengths = [35.5, 41.0, 36.5, 36.0]
materials = ['steel', 'copper', 'iron', 'steel']

獲取這些數據並創建表示對象的字典列表的最佳方法是什么,如下所示:

objects = [{'color': 'red', 'width': 10.0, 'length': 35.5, 'material': 'steel'}, {'color': 'blue', 'width': 12.0, 'length': 41.0, 'material': 'copper'}, {'color': 'green', 'width': 8.0, 'length': 36.5, 'material': 'iron'}, {'color': 'black', 'width': 22.0, 'length': 36.0, 'material': 'steel'}]

我目前正在使用 for 循環:

for color in colors:
    obj = {}
    obj['color'] = color
    obj['width'] = widths[colors.index(color)]
    obj['length'] = lengths[colors.index(color)]
    obj['material'] = materials[colors.index(color)]
    objects.append(obj)

但這對於大列表來說很慢所以我想知道是否有更快的方法

這個答案結合了使用列表推導來輕松創建列表和zip()內置 function 並行迭代多個可迭代對象。

objects = [{"color": c, "width": w, "length": l, "material": m} for c, w, l, m in zip(colors, widths, lengths, materials)]

使用range function:

colors = ['red', 'blue', 'green', 'black']
widths = [10.0, 12.0, 8.0, 22.0]
lengths = [35.5, 41.0, 36.5, 36.0]
materials = ['steel', 'copper', 'iron', 'steel']
objects = []
for i in range(len(colors)):
    d = {}
    d['colors'] = colors[i]
    d['widths'] = widths[i]
    d['lengths'] = lengths[i]
    d['materials'] = materials[i]
    objects.append(d)

請注意,所有列表的元素數量必須與colors相同。

zip function 非常有用。

objects = []
for object in zip(colors, widths, lengths, materials):
    objects.append({
        'color': object[0], 
        'width': object[1], 
        'length': object[2], 
        'material': object[3]})
zipped = zip(colors, widths, lengths, materials) objects = [{"color": color, "width": width, "length": length, "material": material} for color, width, length, material in zipped]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM