繁体   English   中英

错误遍历列表

[英]False iteration over list

我有一个函数,假设给定单词包含该字母,则该函数可以最大程度地减少列表中字母的数量。 那就是函数的定义:

word = 'better'
hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3}
def updateHand(hand, word):
    handCopy = hand.copy()
    for x in word:
        print(x)
        print(hand)
        handCopy[x] = hand.get(x,0) - 1
        print(handCopy)
    return handCopy

这就是输出:

b
{'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3}
{'s': 3, 'b': 0, 'z': 1, 't': 2, 'r': 1, 'e': 3}
e
{'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3}
{'s': 3, 'b': 0, 'z': 1, 't': 2, 'r': 1, 'e': 2}
t
{'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3}
{'s': 3, 'b': 0, 'z': 1, 't': 1, 'r': 1, 'e': 2}
t
{'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3}
{'s': 3, 'b': 0, 'z': 1, 't': 1, 'r': 1, 'e': 2}
e
{'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3}
{'s': 3, 'b': 0, 'z': 1, 't': 1, 'r': 1, 'e': 2}
r
{'s': 3, 'b': 1, 'z': 1, 't': 2, 'r': 1, 'e': 3}
{'s': 3, 'b': 0, 'z': 1, 't': 1, 'r': 0, 'e': 2}
Out[110]: {'b': 0, 'e': 2, 'r': 0, 's': 3, 't': 1, 'z': 1}

为什么我的函数跳过第二个t和/或没有从列表中消除它? 谢谢!

让我们考虑这种情况:

hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3}

因此,我们有作为命令。 现在我们执行以下操作:

x = hand.get('t',0) - 1
print x

结果将为1。让我们再做一次:

x = hand.get('t',0) - 1
print x

再次1.为什么? 因为您不是要更新't'键字典的值。 因此,情况与您的代码相同:

handCopy[x] = hand.get(x,0) - 1

因此,您应该采用以下方式:

handCopy[x] = handCopy.get(x, 0) - 1

word = 'better'
hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3}
def updateHand(hand, word):
    handCopy = hand.copy()
    for x in word:         
        print(x)           
        print(hand)        
        handCopy[x] = handCopy.get(x,0) - 1
        print(handCopy)    
    return handCopy

结果:

b
{'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1}
{'s': 3, 'b': 0, 'e': 3, 't': 2, 'r': 1, 'z': 1}
e
{'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1}
{'s': 3, 'b': 0, 'e': 2, 't': 2, 'r': 1, 'z': 1}
t
{'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1}
{'s': 3, 'b': 0, 'e': 2, 't': 1, 'r': 1, 'z': 1}
t
{'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1}
{'s': 3, 'b': 0, 'e': 2, 't': 0, 'r': 1, 'z': 1}
e
{'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1}
{'s': 3, 'b': 0, 'e': 1, 't': 0, 'r': 1, 'z': 1}
r
{'b': 1, 'e': 3, 's': 3, 'r': 1, 't': 2, 'z': 1}
{'s': 3, 'b': 0, 'e': 1, 't': 0, 'r': 0, 'z': 1}
Out[110]: {'s': 3, 'b': 0, 'e': 1, 't': 0, 'r': 0, 'z': 1}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM