有人能告诉我如何在程序找到后从列表中打印这个单词吗?
all_text = input("Please enter some text").lower().split()
keyword_list = ["motorcycle","bike","cycle","dirtbike"]
second_list = ["screen","cracked","scratched"]
if any(word in keyword_list for word in all_text):
print("Keyword found")
if any(word in second_list for word in all_text):
print("Keyword found")
elif any(word in second_list for word in all_text):
print("keyword found")
答案 0 :(得分:0)
如果我正确阅读此内容,那么如果它在以太list
中,则需要相同的内容。如果你想拆分它,你可以做elif
。
all_text = input("Please enter some text").lower().split()
keyword_list = ["motorcycle","bike","cycle","dirtbike"]
second_list = ["screen","cracked","scratched"]
for word in all_text:
if word in second_list or word in keyword_list:
print("Keyword found " + word)
答案 1 :(得分:0)
使用普通for
循环比any
更容易执行此任务
all_text = input("Please enter some text").lower().split()
keyword_list = ["motorcycle","bike","cycle","dirtbike"]
second_list = ["screen","cracked","scratched"]
for word in all_text:
# note that you can't use word in keyword_list
# because it'll also match bike with dirtbike etc.
for keyword in keyword_list:
if word == keyword:
print("Word " + word + "in first keyword list")
break
for keyword in second_list:
if word == keyword:
print("Word " + word + "in second keyword list")
break
答案 2 :(得分:0)
您似乎已经掌握了Python中in
的使用方法,但对于未来的读者,我会注意到Python的in
可用于隐式搜索列表和比较两个列表中的元素时避免第二个for
循环。
all_text = input("Please enter some text").lower().split()
keyword_list = ["motorcycle","bike","cycle","dirtbike"]
second_list = ["screen","cracked","scratched"]
for word in all_text:
if word in keyword_list:
print("Word '{}' found in keyword_list".format(word))
elif word in second_list:
print("Word '{}' found in second_list".format(word))
"有谁能告诉我如何打印这个词(...)" ?
Python支持至少三种动态创建字符串的方法......
一个printf
- ish风格,对于C编码员来说可能看起来很熟悉:
>>> "Inserted word: %s" % "Hi!"
'Inserted word: Hi!'
>>>
使用str
s format
方法:
>>> "Inserted word: {}".format("Hi!")
'Inserted word: Hi!'
>>>
(Ab)使用+
运算符:
>>> "Inserted word: " + "Hi!"
'Inserted word: Hi!'
>>>