Ad

Move To Next Item In List1 When Item From List2 Is Found, When Both Lists Are Compared

- 1 answer

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.

Ad

Answer

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
Ad
source: stackoverflow.com
Ad