【问题标题】:print dictionary key's minus the list variables打印字典键减去列表变量
【发布时间】:2014-09-27 01:26:31
【问题描述】:

所以我试图让游戏拼字游戏,但我有一个小问题,我会尽力解释它:

我写了一个函数,它生成一个有 7 个键的字典(键是你在拼字游戏中得到的字母,键的值表示我手里拿着那个字母的次数)

def deal_hand (7)

生成例如代码:

{'a': 1, 'b': 2, 'k': 1, 'o': 1, 'p': 1, 'r': 1}

这意味着我们有以下字母:a、b、b、k、o、p、r(我们有 2 次 a B,因为那个键的值是 2。

但是现在我想创建一个名为 update_hand 的第二个函数,这个函数应该从 word_list 中获取用户创建的单词(在本例中类似于单词“bob”),并且应该返回以下 2 个字典之一

{'a': 1, 'b': 0, 'k': 1, 'o': 0, 'p': 1, 'r': 1}


{'a': 1, 'k': 1, 'p': 1, 'r': 1}

我的程序应该返回这些程序之一,因为用户使用了字母:B、O 和 B。所以没有剩下 B 和 O。

我现在已经尝试了很多来解决这个问题,我想出了以下功能:

def update_hand(word, hand):
    newd = {}
    for x in word:
        if x in newd:
           newd[x]+=1
    else:
       newd[x] = 1
    hand[x]-=1

    return newd

在这段代码中,函数中 word 和 hand 的值是:

test_word = raw_input("Enter the word you want to make out of these letters.")

print update_hand(test_word,de_letters)

我认为我很接近,但我只是得到我输入的最后一个字母的输出,请帮助我! :o

【问题讨论】:

    标签: list python-2.7 dictionary key key-value


    【解决方案1】:
    def update_hand(hand, name):
        delkeys = []
        for n in name:
            if not hand[n]:
                raise ValueError("Cannot remove %s from hand" %n)
            hand[n] -= 1
            if not hand[n]:
                delkeys.append(n)
        for k in delkeys:
            hand.pop(k)
        return hand
    

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2019-02-01
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 2016-01-21
      相关资源
      最近更新 更多