为什么地图功能无效?

Mun*_*nna 1 python dictionary class python-3.x

我没有受到打击或任何事情,但我觉得这很奇怪。以下是我处理过的代码片段:

from hashClass import HashTable

a = HashTable(11)
input_value = list((54,26,93,17,77,31,44,55,20))

map(lambda x: a.put(x,x),input_value))
print(a.data)
Run Code Online (Sandbox Code Playgroud)

我创建了自己的哈希表类。它有一个叫做 put 的方法,它接受键值对,“HashTable.data”属性显示表中的所有值。

当我对普通键值对使用 put 方法时,它完全正常。我知道可以使用以下方法实现该解决方案:

for i in input_value: a.putt(i,i)
Run Code Online (Sandbox Code Playgroud)

但是我想知道为什么地图功能不起作用?当我尝试使用“put”方法映射每个 input_value 时,如果我没有错,它必须将该值添加到实例中。我的原因是我可能没有使用映射的值,但在我映射时在语法上,它应该更新实例变量。

下面是我创建的哈希类以供参考。

class HashTable(object):

    def __init__(self,size):
        self.size = size
        self.slots = self.size*[None]
        self.data = self.size*[None]
        self.values = 0

    def put(self,key,value):
        hashValue = self.hashFunction(key)
        if self.slots[hashValue] == None:
            self.slots[hashValue] = key
            self.data[hashValue] = value
            self.values += 1
        elif self.slots[hashValue] == key:
            self.data[hashValue] = value
        else:
            hashValue = self.reHash(hashValue)
            while self.slots[hashValue] != None and self.slots[hashValue] != key:
                hashValue = self.reHash(hashValue)
            self.slots[hashValue] = key
            self.data[hashValue] = value
            self.values += 1


    def reHash(self,oldValue):
        return (oldValue+1)%self.size

    def __len__(self):
        return self.values


    def get(self,key):
        hashValue = self.hashFunction(key)
        if self.slots[hashValue] == None:
            return "No Value associated"
        elif self.slots[hashValue] == key:
            return self.data[hashValue]


    def hashFunction(self,key):
        return key%self.size
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 6

我将在这里尝试一下,假设您使用的是 Python3。

使用 python3,amap促进了惰性求值,这意味着除非确实需要,否则它不会执行其功能。您要做的是使用 amap来产生副作用。当然,你可以这样做:

list(map(lambda x: a.put(x,x), input_value)))
Run Code Online (Sandbox Code Playgroud)

要进行的list()力评估。

然而,使用mapfor 副作用在某种程度上是一种反模式。我更喜欢更清晰、更地道的东西,比如for你提到的循环。


举个例子:

In [854]: s = set()

In [862]: m = map(lambda x=x: s.add(x), [1, 2, 3])

In [863]: s
Out[863]: set()
Run Code Online (Sandbox Code Playgroud)

s到目前为止什么也没发生。现在,应用list()map对象。

In [864]: list(m)
Out[864]: [None, None, None]
Run Code Online (Sandbox Code Playgroud)

Nones为副作用的典型症状。然而...

In [865]: s
Out[865]: {1, 2, 3}
Run Code Online (Sandbox Code Playgroud)

所以,它有效。但它肯定不好看。