python - 关于 Dict 的 if 语句

标签 python if-statement dictionary

尝试编写一个函数,如果 wordlist 中且仅由 hand 中的字母组成,则返回 True。我可以很好地检查 list 中是否存在 word,但无法弄清楚如何迭代以检查第二部分。以下错误返回 True:

    word = 'chayote'
    hand = {'a': 1, 'c': 2, 'u': 2, 't': 2, 'y': 1, 'h': 1, 'z': 1, 'o': 2}
    list = ['peach', 'chayote']

    def ValidWord(word, hand, list):
        if word in list:
            for i in word:
                if i in hand:
                    return True
                return False
        else:
            return False

ValidWord(word, hand, list)

最佳答案

解决此问题的最简单方法是使用 collections.Counter ,像这样

from collections import Counter
def is_valid_word(word, hand, list):
    if word in my_list:
        return len(Counter(word) - Counter(hand)) == 0
    return False

my_list = ['peach', 'chayote']
hand = {'a': 1, 'c': 2, 'u': 2, 't': 2, 'y': 1, 'h': 1, 'z': 1, 'o': 2}

print is_valid_word("chayote", hand, my_list)
# False
print is_valid_word("peach", hand, my_list)
# False

关于python - 关于 Dict 的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22468399/

相关文章:

python - 使用 Python 键盘解锁 Windows

python - 使用threading模块在python中实现线程

c# - 在 'if' 语句中混淆使用逗号

ios - 如何使用嵌套的 NSDate 属性将 Realm 对象转换为 JSON?

python - 添加键的值并根据键在 Python 字典列表中的出现对其进行排序

python - 将 python 字典写入 CSV 列 : keys to first column, 值到第二个

python - 使用 SqlAlchemy 和 Id 为 PostgreSQL 创建夹具数据

python - ImageFont.textsize() 返回值的单位是什么?

c++ - 当结构在 C++ 中为真或假时明确

java - 为什么这个循环总是返回 false?