gpt4 book ai didi

python - 从 Python 中的几个列表构建字典列表

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:33 25 4
gpt4 key购买 nike

我有几个这样的列表:

Pargs = [args.Pee, args.Pem,...,args.Pet] # 9 elements of boolean type
indices = [(0,0),(0,1),...,(2,2)] # 9 possible combinations (i,j), i = 0,1,2; j = 0,1,2
D = [{},{},...,{}] # 9 dictionaries, desired result

我想看到的结果应该是这样的:

D = [{event:args.Pee,i:0,j:0},{event:args.Pem,i:0,j:1},...{event: args.Pet,i:2,j:2}]

字典必须如上所示排序。

我试过了

for d in D:
for i in range(3):
for j in range(3):
d['i'],d['j'] = i,j

但这并不能解决问题。我用 zip()、product()、dict() 尝试了很多算法,但都无济于事……

最佳答案

通过理解和 OrderedDict,演示:

from collections import OrderedDict
pargs = ['arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6', 'arg7', 'arg8', 'arg9']
indices = ((x,y) for x in range(3) for y in range(3))
result = [OrderedDict([('event',p), ('i',i), ('j',j)]) for p,(i,j) in zip(pargs, indices)]
print(result) # [OrderedDict([('event', 'arg1'), ('i', 0), ('j', 0)]), OrderedDict([('event', 'arg2'), ('i', 0), ('j', 1)]), OrderedDict([('event', 'arg3'), ('i', 0), ('j', 2)]), OrderedDict([('event', 'arg4'), ('i', 1), ('j', 0)]), OrderedDict([('event', 'arg5'), ('i', 1), ('j', 1)]), OrderedDict([('event', 'arg6'), ('i', 1), ('j', 2)]), OrderedDict([('event', 'arg7'), ('i', 2), ('j', 0)]), OrderedDict([('event', 'arg8'), ('i', 2), ('j', 1)]), OrderedDict([('event', 'arg9'), ('i', 2), ('j', 2)])]

编辑

如果我误解了您的要求并且字典中的顺序并不重要,您可以在没有 OrderedDict 的情况下这样做:

result = [{'event':p, 'i':i, 'j':j} for p,(i,j) in zip(pargs, indices)]

关于python - 从 Python 中的几个列表构建字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35225767/

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