简体   繁体   English

如何通过搜索单词是否在该元素中来打印python中列表的特定元素?

[英]How to print a specific element of a list in python by searching if a word is in that element?

I have a list, each element is a string with a name and a location. 我有一个列表,每个元素都是一个带有名称和位置的字符串。 I'm trying to print all the strings in the list which contain a specific name or location. 我正在尝试打印列表中包含特定名称或位置的所有字符串。

I can print a specific string using the index, and I can check if a string of the list contain a specific keyword (like a location name) but I don't know how to print the results. 我可以使用索引打印一个特定的字符串,我可以检查列表的字符串是否包含特定的关键字(如位置名称),但我不知道如何打印结果。 Thanks for any help, I'm new to python. 感谢您的帮助,我是python的新手。

list = open("list.txt", "r")
keyword = input("instert keyword: ")

for element in list.readlines():
  print(element)
list.close()
#this print out every element in the list
#how can I print an element which contains a specific keyword?

Use the in keyword, so during the loop: 使用in关键字,所以在循环期间:

for element in my_list.readlines():
  if 'target_word' in element:
      print(element)

That should work. 这应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM