功能的实现

2024-10-03 19:28:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我的一个函数实现有问题。在

这样做的目的是减少字典手上的键(如果它在单词中)的值。 例如:

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

->函数更新\u hand(word,hand)

^{pr2}$

所以我试着:

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'

所以我试着在一个测试文件中实现它(只是为了抢劫),一切都很好。。。我不知道我做错了什么。在

谢谢, 菲利普


Tags: 函数inpyhomegetifupdateword
2条回答

为了真正地回答这个问题:您将函数定义为def update_hand(hand, word),但显然您将其称为update_hand(word, hand)。dict和str都是iterable和sizeable,但是str没有get方法。在

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

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

解决问题后,不要忘记删除print语句。在

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

^{pr2}$
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使此任务变得微不足道

相关问题 更多 >