python - 检查Python中的字母列表中是否包含字符串的所有字母

标签 python

我正在尝试用 Python 编写一个 Scrabble 有效单词检查器函数。我需要查看列表是否包含单词中的所有字母,但是一旦匹配了某个字母,我就无法再次使用它。因此,如果我的单词是 'test' 并且我的列表是 ['t', 'a', 'e', 's'],那么应该返回 False,因为我需要 2 个 t。

这是我的想法:

def validWord(word, letterList):
  for x in word:
    if x in letterList:
      letterList = letterList.remove(x)
    else:
      return False
  return True

但是,当我编译它时,出现此错误: TypeError:“NoneType”类型的参数不可迭代

现在我猜测“if x in letterList”只能运行一次而不能迭代。所以现在我希望有人能插入我朝正确的方向前进。这对我来说只是为了好玩,我打算用它来创建一个“Words with Friends Cheaker”并向我的 friend 们展示。

谢谢!

最佳答案

list.remove 返回 None 并且您将其分配给 letterList。在下一次迭代中,它变为 if x in None,其中 in 运算符尝试迭代 None 并因该错误而失败。所以,改变一下

letterList = letterList.remove(x)

letterList.remove(x)

你可以这样解决这个问题

from collections import Counter

def validWord(word, letterList):
    word2, word1 = Counter(word), Counter(letterList)
    return all(word2[k] <= word1.get(k, 0) for k in word2)

print validWord("test", ["t", "a", "e", "s"])  # False
print validWord("test", ["t", "e", "t", "s"])  # True

关于python - 检查Python中的字母列表中是否包含字符串的所有字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187988/

相关文章:

python - 列表列表中的DataFrame

python - 根据 Python Pandas 中的相邻行计算值

python - OpenAI GPT-3 API : Which file formats can be used for fine-tuning?

python - 属性错误 : 'Bot' object has no attribute 'add_roles'

python - 使用Gstreamer的音频录制脚本质量很差

python - Python/OpenCV/OSX 中的鼠标回调事件标志?

python - 变换/扭曲坐标

python - 从字典/JSON 构建层次结构

python - 从包 : "from .* import *" 导入所有函数

python | 26个名为a-z的列表,每个字母都是字符串,随机选择字母,如何选择列表