检查n是否在数组中

时间:2016-11-29 19:14:35

标签: python arrays python-3.x

我想在Python 3中创建一个程序,允许用户输入单词所具有的字母数量以及一些字母。

例如:

>> Input how many letters there are in the word
> 5

>> Put _ if no letter is shown, and letter that is shown down
> _ell_

>> Possible finds: Hello, Mello
>> Update the search
> Hell_

>> Final find: Hello
>> Restart?:
> Yes

我真的不知道如何用恰当的语言解释这一点,但你是开发人员所说的,所以我确定你明白这一点。

您让用户输入单词中的字母数量。 然后你将user input _作为空白字母和正确的字母显示(st_ing >> string) 然后它会提出一些与字典数组或文本文件中的搜索匹配的单词(By array我的意思是words = ["word1", "word2", word3"]等。) 然后,如果查找不超过1,您可以键入以缩小搜索范围 一旦只有1个查找,它将提示重新启动,然后是=重新启动。

我是python的新手,所以这对我来说可能是最复杂的,这就是我问你的原因!

我问这是多么复杂,如果有可能的话,我该怎么做呢。我已经开始了,这就是我现在所拥有的:(记住我刚刚开始)

two_word = ["hi", "ai", "no", "id"]
three_word = ["run", "buy", "tie", "bit", "fat"]
four_word = ["help", "file", "edit", "code", "user"]
five_word = ["couch", "cough", "coach", "stars", "spoon", "sunny", "maths"]

letter_count = input("How much letters are there?: ")
letter_count = int(letter_count)

if letter_count == 2:
    wordlist = two_word

elif letter_count == 3:
    wordlist = three_word

elif letter_count == 4:
    wordlist = four_word

elif letter_count == 5:
    wordlist = five_word

else:
    print("Improper entry.")


guess = input("The word right now: ")

blanks = guess.count("_")
#I don't know how to check for certain letters and how to convert _ to the word in the wordlist
#That is why I'm asking

1 个答案:

答案 0 :(得分:0)

如果我正在开发这个,我会:

  • 将所有字词保留在一个set
  • 略过第一个问题(您可以按第二个问题的长度确定字长)
  • 为您询问用户的每个问题设置一个while循环,以便在无效输入时重复相同的问题。

要检查单词,您可以compile a regular expression并将所有_替换为. s:

regex = re.compile(guess.replace('_', '.') + '$')

现在你正在等待的部分,检查集合中的项目是否匹配:

match = [m.group(0) for word in wordlist for m in [regex.match(word)] if m]
print(' '.join(match) or "No matches")
  

上面的列表推导基本上遍历列表中的每个单词(如果您愿意,可以按长度预先过滤),然后检查它是否与之前创建的正则表达式匹配。如果匹配,m将是Match Object,您可以将第一组中的所有单词组合在一起作为匹配的单词列表。< / p>      

最后一行打印所有以空格分隔的匹配,或者&#34;不匹配&#34;如果没有任何匹配。

此代码未经测试,我不熟悉Python 3,因为我使用Python 2.祝你好运!