繁体   English   中英

Python:多维列表作为字典中键的值

[英]Python: Multi dimensional list as the value to a key in dictionary

d1 = {}   
d2 = {}   
l1 = [1, 2, 3]   
l2 = [4, 5, 6]   

选择A:将字典的第一个键初始化为空列表

d1[0] = []   
d1[0].append(l1)   
d1[0].append(l2)   
print(d1)   
{0: [[1, 2, 3], [4, 5, 6]]}  

选择B:不将字典的第一个键初始化为空列表

d2[0] = l1    
d2[0].append(l2)     
print (d2)    
{0: [1, 2, 3, [4, 5, 6]]}

我正在学习Python。 有人可以解释一下为什么我看到A和B之间的行为不同。我想用A编码行为,但是不明白为什么B给出不同的结果。 谢谢。

d2[0] = [l1]   # this needs to be a list containing l1    
d2[0].append(l2)     
print (d2)    

这是因为,

情况1:

d1[0] = [] # you assign a empty list to your 0 key of dict d1
d1[0].append(l1) #you append a list to the empty list {0: [[1, 2, 3]]}
d1[0].append(l2) #you append a list to the existing list
print(d1)   
{0: [[1, 2, 3], [4, 5, 6]]} 

案例2:

d2[0]=l1 # you assign a list to your 0 key of dict d2
d2[0].append(l2) # now you append l2 list to list l1. That is l2 is added as the last element of l1
print (d2) 
{0: [1, 2, 3, [4, 5, 6]]}

情形3:

d3={}
d3[0] = [l1] # you assign a list with element l1 in it to your 0 key of dict d2 and 
d3[0].append(l2) # now you append l2 list to list that already contains l1. That is l1 is the first element and l2 is the second element
print (d3)

选择A中 :您为d1[0]分配了一个空列表[] ,随后将l1l2作为两个新元素附加到列表[]

选择B中 :您已将l1自身分配给d2[0]并且仅将l2作为一个新元素附加到l1

您必须记住将[]分配给变量将在内存中创建新的列表对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM