将嵌套for循环的输出附加到空字典中,只将最后一个输出添加到字典中



我正在解决一个问题,我想将for循环的每个输出添加到for循环之前已经创建的空字典中。但问题是,我要么只获得字典中最后一项的值,要么获得字典中每一行的相同值。

下面是我所做的一个例子:

#create 2 lists to loop through
list1= [10,20,30, 40, 50, 60]
list2= [1,2,3,4,5,6]
#create empty dict with list1 as the keys
n = { k: [] for k in list1 }
#create empty list and fill it in with loop
a=[]
for i in list1:
for j in list2:
b= 10*j+i   
print(b)
a.append(b)

# fill in the dict
n[i]=a
print(n)

输出:

{10: [], 20: [], 30: [], 40: [], 50: [], 60: [70, 80, 90, 100, 110, 120]}

当我缩进n[I]时,会发生这种情况:

#create 2 lists to loop through
list1= [10,20,30,40,50,60]
list2= [1,2,3,4,5,6]
#create empty dict with list1 as the keys
n = { k: [] for k in list1 }
#create empty list and fill it in with loop
a=[]
for i in list1:
for j in list2:
b= 500*j+i        
a.append(b)
# fill in the dict
n[i]=a

print(n)

输出:

{10: [70, 80, 90, 100, 110, 120], 20: [70, 80, 90, 100, 110, 120], 30: [70, 80, 90, 100, 110, 120], 40: [70, 80, 90, 100, 110, 120], 50: [70, 80, 90, 100, 110, 120], 60: [70, 80, 90, 100, 110, 120]}

我想要的地方:

{10: [20, 30, 40, 50, 60, 70], 20: [30, 40, 50, 60, 70, 80], 30: [40, 50, 60, 70, 80, 90], 40: [50, 60, 70, 80, 90, 100], 50: [60, 70, 80, 90, 100, 110], 60: [70, 80, 90, 100, 110, 120]}
我希望有人知道我做错了什么。提前感谢!

a=[]在循环之外,所以它总是指向同一个列表。您需要在外部for循环中初始化它,这样在每次迭代中您都可以获得指向新列表的指针,您可以将该列表赋值给每个字典值。

#create 2 lists to loop through
list1= [10,20,30, 40, 50, 60]
list2= [1,2,3,4,5,6]
#create empty dict with list1 as the keys
n = { k: [] for k in list1 }
#create empty list and fill it in with loop
for i in list1:
a=[]
for j in list2:
b= 10*j+i   
a.append(b)
n[i]=a
print(n)

您实际上甚至不需要定义a列表。可以直接将空列表作为字典的值:

for i in list1:
n[i] = []
for j in list2:
b= 10*j+i   
n[i].append(b)

最新更新