Python列表内列表乘以10并实现哈希表时得到不同的结果

2024-05-15 07:40:27 发布

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

嘿,伙计们,所以我试图用Python实现一个简单的哈希表,只是好奇为什么这不起作用,所以当我初始化map变量时,我第一次使用这个。你知道吗

class HashMap:
    def __init__(self):
        self.size = 10
        self.map = [[] for _ in range(10)] #What to focus on 

    def getHash(self, key):
        return key % self.size

    def add(self,key, value):
        #Get hashed bucket index
        bucket = self.getHash(key)
        self.map[bucket].append(value)


#To test my function. 
h = HashMap()

h.add(1, "Swag")

print(h.map)

当我这样做的时候,我的哈希映射工作得非常好,得到了想要的结果:

[[], ['Swag'], [], [], [], [], [], [], [], []]

但是,当我这样做时:

self.map = [[]] * 10 #What to focus on

然后我得到这个输出:

[['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag'], ['Swag']]

有人知道为什么会这样吗?我是一个Python新手所以任何东西都会很好谢谢!你知道吗


Tags: tokeyselfaddmapsizebucketvalue
3条回答

使用重复操作符*创建列表列表创建一个包含元素的列表,其中每个列表项引用相同的内存位置。你知道吗

Note: if you will modify any of these 5 items (in the below code example). It indirectly means to update the value of other items (with the same value) as well.

You can print the id of list elements in both the cases using id() function. It's clear in below code example with output.

# First case
list1 = [[67]] * 5
print(list1);
print(id(list1[0]))
print(id(list1[1]))
print(id(list1[2]))
print(id(list1[3]))
print(id(list1[4]))

"""
[[67], [67], [67], [67], [67]]
140366629136392
140366629136392
140366629136392
140366629136392
140366629136392
"""

列表理解是一个伟大的方式来处理上述问题的最佳(Python)的方式。你知道吗

Note: Unlike above, we can easily create a list of lists where each list item references different memory locations.

We can use id() function print the ids of items and see if it's like in the previous code example.

# Second case
list2 = [[68] for i in range(5)]
print(list2);
print(id(list2[0]))
print(id(list2[1]))
print(id(list2[2]))
print(id(list2[3]))
print(id(list2[4]))

"""
[[68], [68], [68], [68], [68]]
140390813841224
140390813841032
140390813841480
140390813842056
140390813842120
"""

References:List of lists changes reflected across sublists unexpectedly

谢谢。你知道吗

因为您没有调用列表构造函数,所以没有创建任何新的列表对象。列表乘法只是复制对相同元素的引用(在本例中是单个列表)。你知道吗

有效的列表理解

self.map = [[] for _ in range(10)]

相当于

self.map = []
for _ in range(10):
    self.map.append([])

但是[[]]*10大致相当于

self.map = []
ls = [[]]
for _ in range(10):
    self.map.extend(ls)

当你做* 10你不是在复制对象,而是对同一个对象做了10次引用。如果对象是可变的,那么更改一个对象将更改所有对象。你的对象是绝对可变的列表。你知道吗

相关问题 更多 >