How to generate a list of strings in which another string appears

Viewed 168

I need to check if a string exists or not within a larger set of strings and if it does exist to add the string which contains it to another list. I have code that checks the presence ok and it works but it cannot add the string because of my implementation.

Code

test_list = ['temp', 'temperature']

b = ['sunny', 'cloudy', 'stempy', 'temp','newtemperature']

hits = []
hit_name = []
for test_string in b:
    res = any(item in test_string for item in test_list)
    if res == True:
        hit_name.append(item)
    hits.append(res)


# print result 
print('\n'*2, hits)

Desired output

hit_name = ['stempy', 'temp','newtemperature']
3 Answers

You can just do

 hits = [x for x in b if any(s in x for s in test_list)]

Here is a code I should do, using multiprocess if list are very big.

import joblib
from joblib import Parallel,delayed
test_list = ['temp', 'temperature']

b = ['sunny', 'cloudy', 'stempy', 'temp','newtemperature']

hit_name = []

# Using un function to paralleliza it if database is big
def func(x,y):
    if all(c in b[y] for c in test_list[x]):
        return(b[y])

# using the max of processors
number_of_cpu = joblib.cpu_count()
# Prpeparing a delayed function to be parallelized
delayed_funcs = (delayed(func)(x,y) for x in range(len(test_list)) for y in range(len(b)))
# fiting it with processes and not threads
parallel_pool = Parallel(n_jobs=number_of_cpu,prefer="processes")
# Fillig the hit_name List
hit_name.append(parallel_pool(delayed_funcs))
# Droping the None
hit_name = list(set(filter(None, hit_name[0])))
hit_name

enter image description here

For a short & simple solution, see @jussi-nurminen's method using a list comprehension.

If you want to stick with your original approach, its very close! You just need to append test_string (which is the current element in b being checked) instead of item.

test_list = ['temp', 'temperature']

b = ['sunny', 'cloudy', 'stempy', 'temp','newtemperature']

hits = []

for test_string in b:
    if any(item in test_string for item in test_list):
        hits.append(test_string)

print(hits)

This gives the expected output:

['stempy', 'temp', 'newtemperature']
Related