不确定字典为什么会变异 [英] Unsure why dictionary is mutating

查看:76
本文介绍了不确定字典为什么会变异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过MIT Open Courseware对Python进行了自学,并在下面的这段代码中遇到了问题.当我单独运行此函数或在另一个函数中运行此函数时,它会改变最初传递的值"hand",但我不确定为什么.我设置了两个局部变量(hand0和tester),第一个保留初始值,第二个进行迭代.但是,这三个方面都会发生变化,而我只是期望测试人员"能够做到这一点.除了使手"变异外,该功能还可以按预期工作.

Doing a self-study of Python via MIT Open Courseware, and ran into a problem with this bit of code below. When I run this function either alone or within another function, it mutates the originally passed value 'hand', and I am not sure why. I set two local variables (hand0 and tester) to hand, the first to preserve the initial value, and the second to iterate over. However, all three change, while I'm only expecting 'tester' to do so. Other than mutating 'hand', the function works as expected.

(传递给该函数的值在设置的参数内变化:word_list是有效英文单词的列表,word是我在此函数中替换以测试的字符串,hand是字母及其相关计数的字典.调试代码已注释掉.)

(Values as passed to the function vary within set parameters: word_list is a list of valid English words, word is a string that I replace within this function for testing, and hand is a dictionary of letters and their associated counts. Debugging code commented out.)

def is_valid_word(word, hand, word_list):
    """
    Returns True if word is in the word_list and is entirely
    composed of letters in the hand. Otherwise, returns False.
    Does not mutate hand or word_list.

    word: string
    hand: dictionary (string -> int)
    word_list: list of lowercase strings
    """
    hand0 = hand
    tester = hand
    #display_hand(hand)
    #display_hand(tester)
    word = raw_input('test word: ')
    length = len(word)
    disc = True
    for c in range(length):
        if word[c] in tester.keys() and tester[word[c]]>0:
            #print tester[word[c]]
            #display_hand(hand)
            #display_hand(tester)
            tester[word[c]]=tester[word[c]]-1            
        else:
            #print 'nope'
            disc = False
    if word not in word_list:
        disc = False
    #print disc
    #display_hand(hand)
    #display_hand(tester)
    #display_hand(hand0)
    return disc

推荐答案

执行tester = hand时,仅创建对hand对象的新引用.换句话说,testerhand相同的对象.如果您查看了他们的id:

When you do tester = hand, you're only creating a new reference to the hand object. In other words, tester and hand are the same object. You could see this if you checked their id:

print id(tester)
print id(hand)  #should be the same as `id(tester)`

或等效地,与is运算符进行比较:

Or equivalently, compare with the is operator:

print tester is hand  #should return `True`

要复制字典,可以使用.copy方法:

To make a copy of a dictionary, there is a .copy method available:

tester = hand.copy()

这篇关于不确定字典为什么会变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆