Fat*_*teh 2 python list-comprehension dictionary-comprehension
假设我有一个字典列表,如下所示:
final_list = [{'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}]
Run Code Online (Sandbox Code Playgroud)
我有一个看起来像这样的列表:
input_list = [['London', 'New York', 'San Francisco'], [8908081, 8398748, 883305]]
Run Code Online (Sandbox Code Playgroud)
我想正确的价值观,从地图input_list
到final_list
,但我无法弄清楚如何。我想它会是这样的:
n = 0
while n < len(final_list):
for category in input_list:
for section in final_list:
# then here, somehow say
# for the nth item in each of the sections, update the value to nth item in category
# then increment n
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激!提前致谢 :)
这是一个可能的解决方案:
final_list = [{'city': c, 'population': p} for c, p in zip(*input_list)]
Run Code Online (Sandbox Code Playgroud)
以下是内容final_list
:
[{'city': 'London', 'population': 8908081},
{'city': 'New York', 'population': 8398748},
{'city': 'San Francisco', 'population': 883305}]
Run Code Online (Sandbox Code Playgroud)
仅使用基于函数的方法,您甚至可以做一些更有趣的事情。这适用于您可能需要的任意数量的键。
from itertools import cycle
keys = ('city', 'population')
final_list = list(map(dict, zip(cycle([keys]), zip(*input_list))))
Run Code Online (Sandbox Code Playgroud)