[英]Create a loop in Python to find any entry from one list in another list
Is there a way to append only those entries of my help_list
to the final_list
, that include either one of the keywords
and either one of the magazine_names
?有没有办法只将我的
help_list
那些条目附加到final_list
,其中包括一个keywords
和一个magazine_names
?
help_list = ["aa mag1", "aa mag2", "aa mag3", "bb mag4", "aa mag4", "bb mag2", "aa mag3", "cc mag1", "aa mag4", "ii mag4"]
keywords = ["aa", "ii"]
magazine_names = ["mag3", "mag4"]
final_list = []
for entry in help_list:
if any(element in help_list for element in keywords) and any(element in help_list for element in magazine_names):
final_list.append(entry)
print(final_list)
As a side note: For my actual code, the list with the keywords and the list with the magazines include over 100 entries each.附带说明:对于我的实际代码,关键字列表和杂志列表分别包含 100 多个条目。
k_set = set(keywords)
m_set = set(magazine_names)
final_list = [h for h in help_list if h.split()[0] in k_set and h.split()[1] in m_set]
I think this might be what you are looking for:我认为这可能是您正在寻找的内容:
def contains_one(item, search_terms):
"""Returns true iff any item of `search_terms` is contained in item.
"""
for search in search_terms:
if search in item:
return True
return False
if __name__ == "__main__":
help_list = ["aa mag1", "aa mag2", "aa mag3", "bb mag4", "aa mag4", "bb mag2", "aa mag3", "cc mag1", "aa mag4", "ii mag4"]
keywords = ["aa", "ii"]
magazine_names = ["mag3", "mag4"]
final_list = []
for item in help_list:
if contains_one(item, keywords) and contains_one(item, magazine_names):
final_list.append(item)
print(final_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.