2016-04-22 88 views
0

任何人都可以告訴我如何在程序找到它們時從列表中打印單詞?從列表中打印關鍵字

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

如果您沒有保存數據,則很難打印數據。爲什麼不創建一個最初爲空的列表'found_words',當你找到一個單詞時你會追加到這個列表中?另外 - 使用'sets'而不是'lists'完成這種事情要好得多,但是你可能還沒有學過集合。 –

回答

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) 
0

使用普通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: 
    # 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 
+0

感謝lafexlos你給我的解決方案,我需要開始我的gcse第二編程任務:) – liv

0

any容易得多,您似乎對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小號format方法:

>>> "Inserted word: {}".format("Hi!") 
'Inserted word: Hi!' 
>>> 

使用+操作者(AB):

>>> "Inserted word: " + "Hi!" 
'Inserted word: Hi!' 
>>>