Search code examples
pythonfor-loopsearchbreak

list in list, search in an another list


I have a first list, containing string lists and a second list containing strings. I want that when a string from the first list is found in the second, the string from the second is returned and the search resumes at the next string from the first list.

list1 = [
    ['test', 'string'],
    ['hello', 'world']
    ['good', 'morning','everyone']]

list2 = [
    ['test is here'],
    ['hi everyone'],
    ['world of code']]

If list1[0][0] is in list2[0], then return list2[0] and go to list1[1] (don't want to test list1[0][1]).

I've tried nesting for loops inside other for loops with break and if conditions but can't get the solution.


Solution

  • First, here are some tips for solving problems like this in the future:

    First, the format of your input data is pretty strange (in my opinion), so I'd really recommend trying to flatten everything out -- this may or may not be possible depending on the larger structure of your program, so if you can't actually do that, then no big deal. Something like:

    list1 = [ ['test', 'string'], ['hello', 'world'], ['good', 'morning', 'everyone'] ]
    list2 = ['test is here', 'hi everyone', 'world of code']
    

    is already easier to work with from a data processing standpoint, and that's just from flattening list2.

    Second, conceptually, you have to have two loops going on here -- the first is to iterate through list1 (so if you find a match in list2, you can return the match and move onto the next member of list1), and another to go through the individual elements of list1, since a string in list2 could match on any one of the strings from the inner lists in list1 (i.e. a string in list2 could be matched either by 'test' or 'string').

    With that said, here's a (pretty inefficient) solution to your problem:

    def check_long_str(long_strings, check_list):
    
        for check in check_list: #iterate over individual strings in each inner list of list1
            for long_string_item in long_strings: #look for a match in list2
                long_string = long_string_item[0] #weird format
                if check in long_string:
                    print('"{}" found "{}"'.format(check, long_string))
                    return long_string
    
        return None
    
    def check_for_strings(search_strings, long_strings):
    
        toReturn = set()
        for search_list in search_strings: #iterate over inner lists of list1
            found_str = check_long_str(long_strings, search_list)
            if found_str is not None:
                toReturn.add(found_str)
    
        return toReturn
    
    print(check_for_strings(list1, list2))
    

    Output:

    "test" found "test is here"
    "world" found "world of code"
    "everyone" found "hi everyone"
    set(['test is here', 'hi everyone', 'world of code'])