在Python中检查项是否在集合中?

2024-04-25 05:22:24 发布

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

编写一个程序来检查用户输入的单词是否在预先存在的集合中;无论我输入什么单词,程序都返回“False”(即使是我知道的单词在集合中)。代码如下:

name = input("which file would you like to open?  ")
s=input("word?  ")

F = open(name, "r")
words = set()
words.add(F)

def contains(s,words):
    if s in words:
        print("true")
    else:
        print("false")
contains(s,words)

Tags: 代码name程序youfalsewhichinput检查用户
3条回答

正确的方法是使用发电机:

name = input("which file would you like to open?  ")
word_to_look_for=input("word?  ")

def check(word_to_look_for, word_from_file):
    return word_to_look_for == word_from_file

with open(name, "r") as file:
    # The code inside the parentheses () returns a generator object
    word_exists = (check(word_to_look_for, word_from_file.rstrip("\n")) for word_from_file in file.readlines())  

# This will return true if either one of the "check" function results is True 
print(any(word_exists))

假设文件中每行有一个单词,例如

asd
asdf

您可以使用它,它将每一行添加到words

name = input("which file would you like to open?  ")
s = input("word?  ")

F = open(name, "r")
words = set()
for line in F:  # add every line to words (assuming one word per line)
    words.add(line.strip())

def contains(s, words):
    if s in words:
        print("true")
    else:
        print("false")

contains(s, words)

打印输出:

which file would you like to open?  file.txt
word?  asd
true

编辑:对于实际任务来说,这是一种更短的方法:

name = input("which file would you like to open?  ")
s = input("word?  ")

F = open(name, "r")
print("true") if s in F.read() else print("false")

假设您的文件如下所示:

banana
apple
apple
orange

让我们创建该文件:

with open("test.txt","w") as f:
    f.write("banana\napple\napple\norange")

现在让我们运行一个示例代码:

s= input("word?  ")

words = set()

# Using with we don't need to close the file
with open("test.txt") as f:
    # here is the difference from your code
    for item in f.read().split("\n"):
        words.add(item)

def contains(s,words):
    for word in words:
        if s in word:
            print("true")
            break
    else:
        print("false")

contains(s,words)

键入:

apple returns "true"

ap returns "true"

oeoe returns "false"

相关问题 更多 >