2024-04-19 09:11:15 发布
网友
让我们考虑一下这种情况:
hand = {'b':1, 'r':1, 's':3, 't':2, 'z':1, 'e':3}
所以我们有一只手作为听写。现在我们做这个:
x = hand.get('t',0) - 1 print x
结果将是1。我们再来一次:
又是1。为什么?因为您没有更新't'key in hand dict的值。所以情况与代码中的情况相同:
'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}
让我们考虑一下这种情况:
所以我们有一只手作为听写。现在我们做这个:
结果将是1。我们再来一次:
又是1。为什么?因为您没有更新
't'
key in hand dict的值。所以情况与代码中的情况相同:所以你应该这样做:
解决方案
结果:
相关问题 更多 >
编程相关推荐