0

我正在实现字典的重新散列,所以我有 2 个哈希表,我正在尝试将旧的哈希表设置为引用新的哈希表。

我有一些类似的东西:

def fart(hashTable):
    hashTableTwo = mkHashTable(100)
    hashTable = hashTableTwo
def main():
    hashTableOne = mkHashTable(50)
    fart(hashTableOne)
    print(hashTableOne.size)

mkHashTable(50) 生成一个对象 HashTable,其大小为 50。这打印 50,我希望它打印 100。

我所拥有的似乎不起作用。关于如何使其工作的任何想法?我不允许使用全局变量或对象

4

1 回答 1

0

Python 中的赋值 (=) 是名称绑定。

所以hashTable = hashTableTwo在fart函数中不会改变原来的hashTable,它只是将hashTablefart函数中的变量名绑定到hashTableTwo对象上。

检查这篇文章Python 是按值调用还是按引用调用?两者都不。

解决方法取决于 hashTable 的数据结构/对象类型。dict提供一些方法来更新其值。

def update_dict(bar):
    bar = {'This will not':" work"}


def update_dict2(bar):
    bar.clear()
    bar.update(This_will="work")


foo={'This object is':'mutable'}

update_dict(foo)

print foo

>>> {'This object is': 'mutable'}


update_dict2(foo)

print foo

>>> {'This_will': 'work'}
于 2013-10-30T03:49:49.277 回答