我希望确保列表中的项目没有重复的元素不存在于输入的字

2024-04-26 18:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

是的,所以我需要确保列表中的每一项与输入的单词进行比较时,不包含输入单词中不存在的重复元素。这有点难以解释,所以我将展示我目前所掌握的:

listword = input("Inputted word: ")
listcomparison = ["su", "pici", "nope", "pics", "susu", "poici","pic","pooici"]

for line in listcomparison:
word = list(listword)
while len(word) >10:
    word = input("Inputted word needs to be less than or 10 letters long: ")
else:
    imp_letter = word[4]
    wordcount = len(line)

    if wordcount >= 4:
        chars = list(line)


        if imp_letter in line and all(char in word for char in chars):
            print(line)           

我在开始时没有提到,但是代码中的“imp\u单词”是存在的,因为练习中的一个要求是输入单词中的第5个字母必须出现在列表中的所有单词中。你知道吗

问题是,当我运行这个程序时,例如使用输入的单词“dis疑”,它将返回“pici” 图片 波希 普伊西”。问题是,像pooici这样的单词(好吧,“单词”)有重复的元素(比如pooici有两个O)在输入的单词中没有出现,当我应该这样做的时候,它们会出现。。。基本上,输入的单词是允许的字母,每个字符的数量是允许的。你知道吗

我知道我不擅长解释这些东西,但我已经找了差不多一整天的解决办法了。帮一个新手?你知道吗


Tags: in元素列表forinputline单词list
1条回答
网友
1楼 · 发布于 2024-04-26 18:36:57

使用^{}。你知道吗

下面是一些collections.Counter的例子:

>>> Counter("read")
Counter({'a': 1, 'r': 1, 'e': 1, 'd': 1})
>>> Counter("dad") - Counter("read") # two "d" in "dad" minus one "d" in "read" leaves one "d"
Counter({'d': 1})
>>> Counter("ad") - Counter("read") # letters "a" and "d" are in "read"
Counter()
>>> bool(Counter()) # an empty Counter evaluates to False
False

下面是如何编写问题解决方案的代码:

words = ["su", "pici", "nope", "pics", "susu", "poici","pic","pooici"]
letter_counts = Counter("suspicion")
found_words = [word for word in words if not Counter(word) - letter_counts]

found_words包含

['su', 'pici', 'pics', 'poici', 'pic']

相关问题 更多 >