how to fetch whole string if part of the sting is present in list using python

Viewed 33

I want to search the following list, to see if any of the string items contain 'aed'; if so, I want to return the whole string (e.g. 'abc/aed'). How can this be achieved using python/pyspark?

list=['abc/aed','bcd/eac','rtf/reew','opee/rew']
4 Answers

this should work

my_list=['abc/aed','bcd/eac','rtf/reew','opee/rew']
output = [val for val in my_list if "aed" in val]

We can use a list comprehension:

list = ['abc/aed', 'bcd/eac', 'rtf/reew', 'opee/rew']
output = [x for x in list if "aed" in x]
print(output)  # ['abc/aed']
for i in list:
    if "aed" in i:
        print(i)

Use a map for python list. e.g.,

>>> l = ['abc/aed','bcd/eac','rtf/reew','opee/rew']
>>> list(map(lambda x: x if x.find("aed") != -1 else False, l))
['abc/aed', False, False, False]
Related