user10623374
user10623374

Reputation:

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.

Upvotes: 0

Views: 51

Answers (2)

Walter Tross
Walter Tross

Reputation: 12624

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]

Upvotes: 1

pascscha
pascscha

Reputation: 1673

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)

Upvotes: 0

Related Questions