..更好的解决方案。
我有以下3个列表
a = [1, 2, 3]
b = ['a', 'b', 'c']
c = ['aa', 'bb', 'cc']
我需要在这些列表中创建一个字典列表,如下所示:
[{'address': 'aa', 'id': 1, 'name': 'a'}, {'address': 'bb', 'id': 2, 'name': 'b'
}, {'address': 'cc', 'id': 3, 'name': 'c'}]
我用以下代码完成了这项工作。我有兴趣知道有没有更好的办法。
>>> d = [dict(zip(['id', 'name', 'address'], i)) for i in zip(a, b, c)]
>>> d
[{'address': 'aa', 'id': 1, 'name': 'a'}, {'address': 'bb', 'id': 2, 'name': 'b'
}, {'address': 'cc', 'id': 3, 'name': 'c'}]
答案 0 :(得分:3)
怎么样:
from itertools import izip, repeat
a = [1, 2, 3]
b = ['a', 'b', 'c']
c = ['aa', 'bb', 'cc']
addresses = repeat('address')
ids = repeat('id')
names = repeat('names')
d = [dict(((i, j), (k, l), (m, n))) for i, j, k, l, m, n in izip(addresses, a, ids, b, names, c)]
Re:慢 - 我试图简单地对它进行基准测试:
from time import time
t = time()
for i in xrange(100000):
d = [dict(((i, j), (k, l), (m, n))) for i, j, k, l, m, n in izip(addresses, a, ids, b, names, c)]
print time() - t
给出0.68秒,OP的方式给出0.81秒。
Re 2:最快的方式(恕我直言也最简单)是:
d = [{'address': j, 'id': l, 'names': n} for j, l, n in izip(a, b, c)]
给出0.23秒。