我有以下数据结构:
[('dim1', ['All', 'All', 'All']),
('dim2', ['100', '100', '100']),
('min', [1500, 1200, 1300]),
('max', [2500, 2200, 2000]),
('kpi', ['Avg prod', 'Avg prod', 'Sales'])]
我想要以下内容:
[{'dim1': 'All', 'dim2': '100', 'min': 1500, 'max': 2500, 'kpi': 'Avg prod'},
{'dim1': 'All', 'dim2': '100', 'min': 1200, 'max': 2200, 'kpi': 'Avg prod'},
{'dim1': 'All', 'dim2': '100', 'min': 1300, 'max': 2000, 'kpi': 'Avg Sales'}]
我希望能够很好地实现pythonic并尽可能地避免嵌套循环。谢谢!
答案 0 :(得分:5)
>>> lst = [
... ('dim1', ['All', 'All', 'All']),
... ('dim2', ['100', '100', '100']),
... ('min', [1500, 1200, 1300]),
... ('max', [2500, 2200, 2000]),
... ('kpi', ['Avg prod', 'Avg prod', 'Sales'])
... ]
>>>
>>> keys, values = zip(*lst)
>>> [dict(zip(keys, vs)) for vs in zip(*values)]
[{'dim1': 'All', 'max': 2500, 'dim2': '100', 'kpi': 'Avg prod', 'min': 1500},
{'dim1': 'All', 'max': 2200, 'dim2': '100', 'kpi': 'Avg prod', 'min': 1200},
{'dim1': 'All', 'max': 2000, 'dim2': '100', 'kpi': 'Sales', 'min': 1300}]
答案 1 :(得分:1)
Oneliner:
data = [('dim1', ['All', 'All', 'All']),
('dim2', ['100', '100', '100']),
('min', [1500, 1200, 1300]),
('max', [2500, 2200, 2000]),
('kpi', ['Avg prod', 'Avg prod', 'Sales'])]
result = (lambda h, l: [dict(zip(h, i)) for i in zip(*l)])(*zip(*data))
*这实际上与我独立到达的falsetru的答案相同,除了应用程序是lambda。
答案 2 :(得分:1)
Python初学者:
length 3
。使用for loop
方法使用range()
迭代3次。 tmp={}
。代码:
input = [('dim1', ['All', 'All', 'All']),
('dim2', ['100', '100', '100']),
('min', [1500, 1200, 1300]),
('max', [2500, 2200, 2000]),
('kpi', ['Avg prod', 'Avg prod', 'Sales'])]
output = []
for i in range(0,3):
tmp = {}
for j in input:
tmp[j[0]] = j[1][i]
output.append(tmp)
import pprint
pprint.pprint(output)
输出:
vivek@vivek:~/Desktop/stackoverflow$ python 11.py
[{'dim1': 'All', 'dim2': '100', 'kpi': 'Avg prod', 'max': 2500, 'min': 1500},
{'dim1': 'All', 'dim2': '100', 'kpi': 'Avg prod', 'max': 2200, 'min': 1200},
{'dim1': 'All', 'dim2': '100', 'kpi': 'Sales', 'max': 2000, 'min': 1300}]