如何从给定字母中筛选单词列表?

2024-10-06 07:18:42 发布

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

我有一个python程序,我正在尝试创建,用户可以在其中输入一个字母,该程序过滤掉所有不以这个字母开头的单词。不幸的是,我和我的初学者大脑都不知道如何用代码来写,所以有什么帮助吗

我的代码已经:

#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()
#Take the first character of every word and make a new variable to add that to.
firstchar = [x[0] for x in content]

#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")

不像你看到的那么多,但我很自豪。我想我需要使用firstchar[i]u_selected来匹配这两个字母


Tags: andoftheto代码程序adduse
3条回答

如上所述,您可以使用[0]访问字符串的第一个字符。如果符合指定的条件,下面的将为您将每个单词添加到新列表中

chosen_words = [word for word in content if word.lower()[0] == u_selected.lower()]

.lower()只是将所有内容转换为小写,以确保忽略大小写

要筛选您需要执行的操作,请执行以下操作:

#Open list of words file and add to "content" variable
content = open('Word List').read().splitlines()

#Ask the user which letter they'd like to use
print("Which letter would you like to use?")
u_selected = input("> ")
filtered_words = [word for word in content if word.startswith(u_selected)

字符串有自己的方法使使用字符串更容易

dir(str)

可以使用.startswith()测试字符串的开头。比如说,

words     = open('Word List').read().splitlines()
new_words = [word for word in words if word.startswith('A')]

相关问题 更多 >