不清楚您需要什么,请编辑原始问题让我们知道您需要什么输出。但是,这里有一些建议...
第一个问题是;您没有两个列表。您有a
和b
,它们都是嵌套列表的嵌套列表(3级深度),总共涉及14个列表。
a = [ # First level list "a"
[ # Second level list I.e. a[0]
[] # Third level list a[0][0]
],
[ # Second list I.e. a[1]
[0.4, 2] # Third level list a[1][0] = 0.4, a[1][1] = 2
],
[ # Second level list I.e. a[2]
[0.8, 1] # Third level list a[2][0] = 0.8, a[2][1] = 1
]
]
所以你需要决定你想要哪些东西被反转。
第二个问题是Python中“引用”与“复制”的概念。一个好的讨论从这里开始。但简单来说,变量名是对象的引用,而不是对象本身。
因此,当你使用...创建a
时...
a = [[[]], [[0.4, 2]], [[0.8, 1]]]
...你在内存中创建了一个列表对象,变量引用为a
。该列表对象包含对已在内存中创建的三个其他列表对象的引用(a[0]
、a[1]
、a[3]
),每个对象都包含对另一个附加列表对象的引用(a[0][0]
、a[1][0]
、a[2][0]
)。
如果你使用...将a
分配给A
...
a = [[[]], [[0.4, 2]], [[0.8, 1]]]
print ("the memory location for object 'a' is:", hex(id(a)))
A = a
print ("the memory location for object 'A' is:", hex(id(A)), "(The same location)")
b = [i for i in reversed(a)]
print ("the memory location for object 'b' is:", hex(id(b)), "(A different location)")
...a
和A
是同一个对象,但b
是一个新对象。因此,print(a is b)
返回False
。
也就是说...
the memory location for object 'a' is: 0x7fdc65b12308
the memory location for object 'A' is: 0x7fdc65b12308 (The same location)
the memory location for object 'b' is: 0x7fdc65b126c8 (A different location)
然而,正如上面@Derte Trdelnik
所指出的那样,当您创建b时,您只复制了子列表的引用 - 而不是对象。也就是说,
a = [[[]], [[0.4, 2]], [[0.8, 1]]]
b = [i for i in reversed(a)]
print ("the memory location for object 'a' is:", hex(id(a)))
print ("the memory location for object 'b' is:", hex(id(b)), "(A different location)")
print ("the memory location for sub-list object 'a[1]' is:", hex(id(a[1])) )
print ("the memory location for sub-list object 'b[1]' is:", hex(id(b[1])), "(The same location as a[1])" )
输出:
the memory location for object 'a' is: 0x7f49b46f59c8
the memory location for object 'b' is: 0x7f49b46f5a08 (A different location)
the memory location for sub-list object 'a[1]' is: 0x7f49b46f5908
the memory location for sub-list object 'b[1]' is: 0x7f49b46f5908 (The same location as a[1])