如何判断字符串的所有字符均存在于指定列表中?(Python实现)
解决字符串与列表整体比较问题:实现
isWordGuessed函数 你需要实现的这个函数核心需求很明确:验证目标单词secretWord的每一个字母都已经出现在已猜测的字母列表lettersGuessed中,符合条件返回True,否则返回False。
先看看你当前代码的问题:
def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' # FILL IN YOUR CODE HERE... for i in lettersGuessed: if i in secretWord: return True; else: return False;
这个逻辑完全跑偏了——你只检查了lettersGuessed的第一个元素:如果第一个字母在单词里就直接返回True,不在就返回False,完全没完成"所有字母都要匹配"的要求。比如第一个测试用例里,列表第一个元素是z,你的代码会直接返回False,但实际上banana的所有字母都在列表里,正确结果应该是True。
正确的实现方式
方式一:逐字符遍历检查
这是最直观的写法,遍历目标单词的每个字母,确保每个都在已猜测列表中:
def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' # 遍历目标单词的每一个字符 for char in secretWord: # 只要有一个字符不在已猜测列表,直接返回False if char not in lettersGuessed: return False # 所有字符都验证通过,返回True return True
方式二:用all()函数简化代码
Python内置的all()函数可以帮我们一行搞定这个逻辑,它会检查可迭代对象中所有元素是否为True:
def isWordGuessed(secretWord, lettersGuessed): ''' secretWord: string, the word the user is guessing lettersGuessed: list, what letters have been guessed so far returns: boolean, True if all the letters of secretWord are in lettersGuessed; False otherwise ''' return all(char in lettersGuessed for char in secretWord)
这里的生成器表达式会逐个判断secretWord的字符是否存在于lettersGuessed中,只有所有判断结果都是True时,all()才会返回True,完美匹配需求。
测试示例验证
- 运行
print(isWordGuessed('banana', ['z', 'x', 'q', 'b', 'a', 'n', 'a', 'n', 'a'])),会输出True,因为banana的所有字母(b、a、n)都在列表里。 - 运行
print(isWordGuessed('apple', ['a', 'e', 'i', 'k', 'p'])),会输出False,因为apple中的l不在已猜测列表里。
内容的提问来源于stack exchange,提问作者code_conundrum
相关产品推荐
相关产品推荐

