gpt4 book ai didi

python - 创建 key :value pair in the first loop and append more values in subsequent loops

转载 作者:行者123 更新时间:2023-12-02 19:43:57 25 4
gpt4 key购买 nike

如何在第一个循环中创建键:值对,然后在后续循环中附加值?例如:

a = [1,2,3]
b = [8,9,10]
c = [4,6,5]

myList= [a,b,c]
positions= ['first_position', 'second_position', 'third_position']

我想创建一个字典来记录每个字母的位置值:

mydict = {'first_position':[1,8,4], 'second_position':[2,9,6], 'third_position':[3,10,5]}

想象一下,我有数百万个字母,而不是 3 个字母,每个字母有 3 个值。我怎样才能循环遍历每个字母并且:

  1. 在第一个循环中创建键:值对“first_position”:[1]
  2. 在后续循环中将值附加到相应的键:'first_position':[1,8,4]

谢谢!

最佳答案

试试这个代码:

mydict = {}
for i in range(len(positions)):
mydict[positions[i]] = [each[i] for each in myList]

输出:

{'first_position': [1, 8, 4],
'second_position': [2, 9, 6],
'third_position': [3, 10, 5]}

关于python - 创建 key :value pair in the first loop and append more values in subsequent loops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60780943/

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