如何创建词典列表?

2024-04-25 03:49:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建词典列表:

box1 = {'x' : 10, 'y' : 10, 'direction' : 'right'}
box2 = {'x' : 20, 'y' : 10, 'direction' : 'right'}
box3 = {'x' : 30, 'y' : 10, 'direction' : 'right'}
box4 = {'x' : 40, 'y' : 10, 'direction' : 'right'}
box5 = {'x' : 50, 'y' : 10, 'direction' : 'right'}
box6 = {'x' : 60, 'y' : 10, 'direction' : 'right'}
box7 = {'x' : 70, 'y' : 10, 'direction' : 'right'}
box8 = {'x' : 80, 'y' : 10, 'direction' : 'right'}
box9 = {'x' : 90, 'y' : 10, 'direction' : 'right'}

我成功地使用loop只创建了第一个dictionary box1

for i in range(9):
    new_n = 'box' + str(i+1)
    exec(new_n + " = {}")

我可以使用循环和exec方法来创建这样的列表吗? 如果没有,我如何创建它?你知道吗

附言:我找不到一个列表理解的概念,它用字典填充一个列表,并为这些字典指定不同的名称。这就是为什么这个问题不同于这个网站上的任何其他问题。你知道吗


Tags: right列表new字典词典execdirectionbox2
1条回答
网友
1楼 · 发布于 2024-04-25 03:49:10
boxes = {"box%d"%i:{'x' : x, 'y' : 10, 'direction' : 'right'} for i,x in enumerate(range(10,91,10),1)}

print boxes["box1"]

my_var = "box1"
print boxes[my_var]

也许我会这么做

一般来说,您应该避免eval/exec

相关问题 更多 >