我在练习蟒蛇,发现下面的行为,但我不明白为什么。谁能解释一下原因吗?
案例1
a = [[] for i in range(5)]
b = [[]] * 5
a[3].append(3)
b[3].append(3)
print(a) # Output: [[], [], [], [3], []]
print(b) # Output: [[3], [3], [3], [3], [3]]我在a和b上看到了不同的行为,a和b之间有什么区别?
案例2
def test(sentences):
root = {}
for sentence in sentences:
base = root
for word in sentence.split(' '):
if not base.get(word):
base[word] = {}
base = base[word]
return root
print(test(["Hello world", "Hello there"]))
# Output: {'Hello': {'world': {}, 'there': {}}}也许是个问题,但是在第二种情况下,当你没有修改根的时候,它是如何被修改的呢?
发布于 2022-10-09 23:07:47
列表上的*操作将创建一个列表的副本。这是证据,
In [1]: a = [[] for i in range(5)]
...: b = [[]] * 5
In [2]: [id(i) for i in a]
Out[2]: [4649788160, 4640976128, 4647308224, 4647305856, 4643089472]
In [3]: [id(i) for i in b]
Out[3]: [4648966336, 4648966336, 4648966336, 4648966336, 4648966336]对于case2也是如此。
https://stackoverflow.com/questions/74008961
复制相似问题