Search code examples
pythonlistnested

Making list from elements from each level of a nested list


I have a list:

cleaner = [['Re:', '31_300323', 'RE777']]

I want to check if another list contains same value, I write:

any('31_300323' in sl for sl in cleaner)

, and get "True", but if I write:

suka = []
for h in cleaner:
    if any(h in sl for sl in cleaner):
        suka.append(h)

the emptry list remains empty. Why? Thank You


Solution

  • flatten function: used to flatten the nested_list

    Code:

    def flatten(lst):
        """Flattens a nested list of any depth."""
        flattened = []
        for item in lst:
            if isinstance(item, list):
                flattened.extend(flatten(item))
            else:
                flattened.append(item)
        return flattened
    
    cleaner=[['Re:', '31_300323', 'RE777','21_110123'],[[['26_100822']]]]
    zajavki=['21_220223', '21_110123', '23_200123', '26_100822', '25_260123', '31_300323']
    
    # Flatten the nested list
    cleaner_flat = flatten(cleaner)
    suko=[]
    for word in cleaner_flat:
        if word in zajavki:
            suko.append(word)
    print(suko) # ['31_300323','21_110123','26_100822']
    

    Note* If you don't want duplicates you can use data structure set()

    Let's say you known the depth of the nested_list than you don't need to flatten the nested list

    Code:

    cleaner=[['Re:', '31_300323', 'RE777'],['Ze:', '23_200123', 'RE778'],['De:', '21_220223', 'RE779']]
    zajavki=['21_220223', '21_110123', '23_200123', '26_100822', '25_260123', '31_300323']
    
    suko=[]
    
    for sublist in cleaner:
        for check in sublist:
            if check in zajavki:
                suko.append(check)
    print(suko) #['31_300323', '23_200123', '21_220223']