猿问

如何在列表中查找以用户要求的某个字母开头的单词

所以我正在尝试制作一个添加、删除、搜索、保存和加载列表的程序


除了在列表中搜索第一个字母之外,我已经设法使一切正常


程序会询问用户想搜索哪个字母 然后在列表中搜索用户输入的第一个字母


我设法做的是:


mylist = ["hello","world","how","you","doing"]

for word in mylist:

  print (word[0])

它确实打印出每个单词的第一个字母


h

w

h

y

d

>>> 

但我想做什么


mylist = ["hello","world","how","you","doing"]

letter = input("input a letter you would like to search ").lower()

用户输入的字母将在整个列表中搜索


找到所有以该字母开头的单词后,我希望它打印出找到的单词数,然后打印出用户请求的字母中找到的单词


牧羊人nacy
浏览 285回答 4
4回答

达令说

使用列表理解 startswith[i for i in mylist if i.startswith(letter)]它与您正在做的类似,但您没有检查如下条件mylist = ["hello","world","how","you","doing"]for word in mylist:      if word[0]==letter:            print(word)对.lower()列表中存在的字符串进行安全使用mylist = ["Hello","world","how","you","doing"]letter = 'h'[i for i in mylist if i.lower().startswith(letter)] #["Hello","how"]

蝴蝶不菲

mylist = ["hello","world","how","you","doing"]letter = input("input a letter you would like to search ").lower()    input a letter you would like to search 'h'list_starting_with_letter = [i for i in mylist if i[0].lower()==letter.lower()]list_starting_with_letter    ['hello', 'how']print('Number of such words: '+ str(len(list_starting_with_letter)))    Number of such words: 2

慕丝7291255

for word in list:    if input() in word:        print(word)在那条线上的东西。它从列表中获取单词,然后针对该单词测试用户输入。
随时随地看视频慕课网APP

相关分类

Python
我要回答