尝试编写一个函数,如果 word
在 list
中且仅由 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/