Sandra S
Sandra S

Reputation: 35

apply user defined function to a list of lists in python

I have a list of lists in which I want to return the contents of strings within each list that match specific keywords.

THIS IS ORIGINAL LIST:

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

WANT TO APPLY THIS KEYWORD SEARCH:

keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']

RESULT DESIRED:

list_refine = [['summary of the'], ['reveals a lot', 'juniper relationship']]

So far, i have the code to apply to a single list but I don't know how to look that over all the lists. HERE IS CODE FOR ONE LIST:

string1 = list_orig
substr1 = keywords

def Filter(string, substr): 
    return [str for str in string if
             any(sub in str for sub in substr)] 

print(Filter(string1, substr1))

HERE IS RESULT FOR 1 LIST:

['summary of the']

I researched so many ways to loop over the lists of lists. Here is 1 attempt.

for item in string3:
     new.append([])
     for item in items:
        item = Filter(string1, substr1)
        new[-1].append(item)
item

just got a blank list Thanks everyone! Appreciate it :)

Upvotes: 0

Views: 1181

Answers (2)

mikado
mikado

Reputation: 128

Here is an alternative solution without explicit loops

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

def contains_keyword(sentence):
    keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']
    return any([(kw in sentence) for kw in keywords])

list_refine = [
    (sentence for sentence in lst if contains_keyword(sentence))
    for lst in list_orig
]

Upvotes: 0

Sreeram TP
Sreeram TP

Reputation: 11907

You can use a for loop to iterate over the list and another for loop to iterate over the items and keywords like this,

list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']

list_refine = []

for l_inner in list_orig:
    l_out = []
    for item in l_inner:
        for word in keywords:
            if word in item:
                l_out.append(item)
    list_refine.append(l_out)
print(list_refine) # [['summary of the'], ['reveals a lot', 'juniper relationship']]

Upvotes: 1

Related Questions