【问题标题】:Unsure why dictionary is mutating不确定字典为什么会发生变异
【发布时间】:2013-01-13 20:14:07
【问题描述】:

通过麻省理工学院开放课件自学Python,遇到了下面这段代码的问题。当我单独或在另一个函数中运行此函数时,它会改变最初传递的值“hand”,我不知道为什么。我将两个局部变量(hand0 和 tester)设置为 hand,第一个用于保留初始值,第二个用于迭代。但是,这三个都发生了变化,而我只希望“测试人员”这样做。除了改变“手”之外,该函数按预期工作。

(传递给函数的值在设置参数中有所不同:word_list 是有效英文单词的列表,word 是我在此函数中替换以进行测试的字符串,hand 是字母字典及其相关计数。调试代码被注释掉了。)

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

【问题讨论】:

    标签: python dictionary mutated


    【解决方案1】:

    当您执行tester = hand 时,您只是在创建对hand 对象的新引用。换句话说,testerhand同一个对象。如果您查看他们的id,您会看到这一点:

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

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

    print tester is hand  #should return `True`
    

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

    tester = hand.copy()
    

    【讨论】:

    • 伟大的思想都一样!令人惊讶的是,我们的答案以完全相同的措辞开头。
    • @MarkRansom -- 我很乐意和你一起考虑我的想法:-)
    • 感谢您花时间回答我的新手问题。感谢您的帮助。
    • @PhilSaulnier 通过帮助像你这样的新手,他们变得很棒
    • @PhilSaulnier -- 这实际上是我发现人们在 python 中拥有的更困难的概念之一。一旦你弄清楚了,它就会很有意义并且非常有用/强大,但需要一点时间来适应其他语言。
    【解决方案2】:

    当您执行tester = hand 时,您并不是在复制hand,而是在对同一对象进行新的引用。您对tester 所做的任何修改都将反映在hand 中。

    使用tester = hand.copy() 解决此问题:http://docs.python.org/2/library/stdtypes.html#dict.copy

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 2020-11-06
      • 2013-02-04
      • 2014-10-20
      相关资源
      最近更新 更多