0

我对函数的实现有疑问。

目的是减少字典中某个键的值(如果它在单词中)。例如:

word = hi
hand = {'h':2,'i':1}

-> 函数 update_hand(字,手)

hand = {'h'1}

所以我尝试了:

def update_hand(hand, word):
    for letter in range(len(word)):
        if hand.get(word[letter],0) != 0:
            hand[word[letter]] -= 1
            if hand.get(word[letter],0) == 0:
                del hand[word[letter]]
    return hand

但是当我调用它时,我得到:

Traceback (most recent call last):
File "/home/phillip/Desktop/ps3/ps3/ps3a.py", line 168, in <module>
print update_hand('quali', {'a': 1, 'i': 1, 'm': 1, 'l': 2, 'q': 1, 'u': 1})
File "/home/phillip/Desktop/ps3/ps3/ps3a.py", line 162, in update_hand
if hand.get(word[letter],0) != 0:
AttributeError: 'str' object has no attribute 'get'

所以我试图在一个测试文件中实现它(只是用于战利品)并且一切正常......好吧,我不知道我做错了什么。

谢谢,菲利普

4

2 回答 2

1

真正回答这个问题:您将函数定义为,def update_hand(hand, word)但您显然将其称为update_hand(word, hand). dict 和 str 都是可迭代的和相当大的,但 str 没有get方法。

调试此类问题的快速简单方法:在代码中添加打印语句,即:

def update_hand(hand, word):
    print "update_hand(%s, %s)" % (hand, word)
    # code here

解决问题后不要忘记删除打印语句。

同样正如锑所提到的,您不需要丑陋的索引。Jakob 发布了一个简洁的版本,collections.Counter但如果你坚持使用较旧的 (< 2.7.x) Python 版本,这里有一个更规范的实现:

def update_hand(hand, word):
    for letter in word:
        count = hand.get(letter, 0)
        if count > 1:
            # avoids a KeyError if letter was not in hand 
            # XXX spec : should this happen ?
            hand[letter] = count - 1
        else:
            # count is already <= 1 so decreasing it would make it <= 0
            del hand[letter]

    return hand
于 2012-07-04T15:56:57.417 回答
1
from collections import Counter

hand = Counter()

def update_hand(word, hand):
    for token in word:
        if hand[token] == 0:
           del hand[token]
        else: 
           hand[token] -= 1

使用collections.Counter使这项任务变得微不足道

于 2012-07-04T14:56:37.600 回答