gpt4 book ai didi

python - 将列表值应用于字典列表

转载 作者:行者123 更新时间:2023-12-05 09:37:01 25 4
gpt4 key购买 nike

假设我有一个字典列表,如下所示:

final_list = [{'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}, {'city': 'value', 'population': 'value'}]

我有一个看起来像这样的列表列表:

input_list = [['London', 'New York', 'San Francisco'], [8908081, 8398748, 883305]]

我正在尝试将正确的值从 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

任何帮助将不胜感激!提前致谢:)

最佳答案

这是一个可能的解决方案:

final_list = [{'city': c, 'population': p} for c, p in zip(*input_list)]

final_list 的内容如下:

[{'city': 'London', 'population': 8908081},
{'city': 'New York', 'population': 8398748},
{'city': 'San Francisco', 'population': 883305}]

您甚至可以仅使用基于函数的方法来做一些更奇特的事情。这适用于您可能需要的任何个键。

from itertools import cycle

keys = ('city', 'population')
final_list = list(map(dict, zip(cycle([keys]), zip(*input_list))))

关于python - 将列表值应用于字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64588070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com