简体   繁体   中英

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 = ["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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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