slider8p
slider8p

Reputation: 89

Extract sub-list items based on matching strings from a larger list of lists

I have the following search list to be used to search any items in it against a larger list of lists. I would like the results to be the complete sub-lists but I only seem to get the items themselves.

search_list = ['a', 'b', 'x']
list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']
new_lst=[]
for z in list_of_lists:
    yll = [x for x in z if any(w in x for w in search_list)]
    n_lst.append(yll)

Output of new_lst:

new_lst = [['a xh'], ['3 b v'], []]

I was after getting this output instead to show all items inside the resulting lists that match any items from search_list

[['a xh', 'opp'], ['l n', '3b v'], []]

Any suggestions or tips would be appreciated.

Thanks

Upvotes: 1

Views: 967

Answers (3)

pakpe
pakpe

Reputation: 5479

You can use the following set comprehension if you don't mind turning your sublists into tuples:

result = {tuple(sublist) for sublist in list_of_lists for element in sublist for item in search_list
      if item in element}

#output: {('axh', 'opp'), ('l n', '3b v')}

Upvotes: 1

mhhabib
mhhabib

Reputation: 3121

append the sublist to new_list if any character of search_list matches.

search_list = ['a', 'b', 'x']
list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']]

new_list = []
for sub in list_of_lists:
    for l in sub:
        if any(w in l for w in search_list):
            new_list.append(sub)
print(new_list)

# Output
# [['axh', 'opp'], ['l n', '3b v']]

Upvotes: 2

pakpe
pakpe

Reputation: 5479

search_list = ['a', 'b', 'x']
list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']]
new_lst=[]
for sublist in list_of_lists:
    for element in sublist:
        for item in search_list:
            if item in element and sublist not in new_lst:
                new_lst.append(sublist)

print(new_lst)

output: [['axh', 'opp'], ['l n', '3b v']]

Upvotes: 1

Related Questions