简体   繁体   English

如何测试字符串变量以查看它是否在字符串列表中

[英]How do I test a string variable to see if it is in a list of strings

I am using python and coding a game where words have to start with the last letter of the word before, and I am trying to find a method to make my code look at a list of strings that have already been entered and choose a new word that is not one of those from a separate text file I already have set up.我正在使用 python 并编写一个游戏,其中单词必须以之前单词的最后一个字母开头,我试图找到一种方法让我的代码查看已输入的字符串列表并选择一个新单词这不是我已经设置的单独文本文件中的一个。 This is what I have so far but I am unsure what to do next.到目前为止,这是我所拥有的,但我不确定接下来要做什么。 (Note: all of my checks for word viability other than if the word has been said previously work.) (注意:除了之前所说的单词之外,我所有的单词可行性检查都有效。)

def ai_choice(last: List[str]):
previous_word = last[-1]
f = open('english3.txt', 'r')
for line in f:
    if line.lower().strip()[0] == previous_word[len(previous_word) - 1] and line != :
        return True
    else:
        return False

It should look like this它应该是这样的

last_letter = None 
Words_used = []
word = input("your word >>")

if word not in Words_used:
    Words_used.append(word)
else :
    print("word is used")
    
last_letter = word[-1]

print("next word should start with >> ",last_letter)

now you can use a file instead of Words_used and make a function of the above snippet or run in a loop现在您可以使用文件代替Words_used并创建上述代码段的函数或循环运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何测试变量是否属于特定类? - How do I test to see if a variable is part of a specific class? 如何在可变长度列表中打印字符串? - How do I print strings in a variable length list? 如何在Python中找到带有字符串列表的预先存在的变量? - How do I find a preexisting variable with a list of strings in Python? 如何从列表中的某些字符串中删除特定字符串? - How do I remove a specific string from some strings in a list? 如何检查字符串列表中的字符串中是否存在大写字母? - How do I check if there is a uppercase letter in a string within a list of strings? 如何将以下 Python 字符串拆分为字符串列表? - How do I split up the following Python string in to a list of strings? 如何判断是否在较大的字符串中找到了字符串列表? - How do I tell if a list of strings are found within a larger string? 如何检查字符串列表中是否存在字符串,包括子字符串? - How do I check existence of a string in a list of strings, including substrings? 使用可变长度字符串的可变长度列表,如何创建所有组合 - With variable length list of variable length strings, how do I create all combinations 如何检查变量是否在python词典中的列表中? - how do i check to see if a variable is inside a list housed in a dictionary in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM