move to next item in list1 when item from list2 is found, when both lists are compared

Viewed 84

Sorry for complicated title, perhaps example'd be easier.

So I have two lists:

list1 = ['cat', 'dog', 'donkey']
list2 = ['http://cat1.com', 'http://cat2.com', 'http://dog1.com', http://dog2.com']

All I want is script, that "greps" list2 with list1 items but when it finds one ocurence, it moves to another item in list1, so it finds phrase "cat" in "http://cat1.com", then it checks list[1] item: 'dog'. When it's finish it should print all it's findings. I tried using .find() but it's not designed for list types of files.

3 Answers

You can try this:

list1 = ['cat', 'dog', 'donkey']
list2 = ['http://cat1.com', 'http://cat2.com', 'http://dog1.com', 'http://dog2.com']

for item in list1:
    for url in list2:
        if item in url:
            print url
            break

Output:

http://cat1.com
http://dog1.com

A more advanced approach could be:

urls = filter(lambda x: x in list2, list1)
print urls

You can do something like this perhaps:

list1 = ['cat', 'dog', 'donkey']
list2 = ['http://cat1.com', 'http://cat2.com', 'http://dog1.com', 'http://dog2.com']

for animal in list1:
     for site in list2:
             if animal in site:
                     print(f'{animal} : {site}')
                     break                     

Output:

cat : http://cat1.com
dog : http://dog1.com
list1 = ['cat', 'dog', 'donkey']
list2 = ['http://cat1.com', 'http://cat2.com', 'http://dog1.com', 'http://dog2.com']
output = [l2 for l2 in list2 for l1 in list1 if l1 in l2]
print(output)

Also your last item of your list2 is missing an apostrophe.

Related