如何从多个单独的列表中创建一个字典列表?



假设我有四个独立的列表,如下所示:

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()内置函数来并行迭代多个可迭代对象。

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

使用range函数:

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函数非常有用。

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]

相关内容

  • 没有找到相关文章

最新更新