所以我正在尝试制作一个添加,删除,搜索,保存和加载列表的程序
除了在列表中搜索第一个字母之外,我还设法使一切正常工作
程序将询问用户要搜索的字母 然后它将在列表中搜索用户输入的第一个字母
我所要做的就是:
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()
将在整个列表中搜索用户输入的字母
找到所有以字母开头的单词后, 我希望它打印出找到的单词数,然后打印出与用户要求的字母一起找到的单词
答案 0 :(得分:2)
在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"]
答案 1 :(得分:0)
for word in list:
if input() in word:
print(word)
那条线上的东西。它从列表中获取单词,然后针对该单词测试用户输入。
答案 2 :(得分:0)
您可以使用列表推导:
mylist = ["hello","world","how","you","doing"]
letter = input("input a letter you would like to search ").lower()
result = [word for word in mylist if word.lower().startswith(letter)]
print(len(result))
print(result)
您可以详细了解List Comprehensions in the docs
的功能编辑(受其他答案启发):
使用word.startswith()
代替索引word[0]
可以避免空字符串的问题。
答案 3 :(得分:0)
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
答案 4 :(得分:0)
mylist = ["hello","world","how","you","doing"]
letter = input("input a letter you would like to search ").lower()
words = list(filter(lambda s: s.startswith(letter), mylist))
print( len(words) )
for w in words: print ("\n"+w)
答案 5 :(得分:0)
希望这对您有帮助
FanOut