Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何生成另一个字符串出现的字符串列表_Python_List_Substring_Any - Fatal编程技术网

Python 如何生成另一个字符串出现的字符串列表

Python 如何生成另一个字符串出现的字符串列表,python,list,substring,any,Python,List,Substring,Any,我需要检查一个字符串是否存在于一组较大的字符串中,以及它是否存在,以便将包含它的字符串添加到另一个列表中。我有检查状态的代码,它正常工作,但由于我的实现,它无法添加字符串 代码 test_list = ['temp', 'temperature'] b = ['sunny', 'cloudy', 'stempy', 'temp','newtemperature'] hits = [] hit_name = [] for test_string in b: res = any(item

我需要检查一个字符串是否存在于一组较大的字符串中,以及它是否存在,以便将包含它的字符串添加到另一个列表中。我有检查状态的代码,它正常工作,但由于我的实现,它无法添加字符串

代码

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)
所需输出

hit_name = ['stempy', 'temp','newtemperature']
你可以这么做

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

下面是我应该做的一个代码,如果列表非常大,则使用多进程

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

有关简短而简单的解决方案,请参阅@jussi nurminen使用列表理解的方法

如果你想坚持你原来的方法,它非常接近!您只需要附加
test\u字符串
(这是正在检查的
b
中的当前元素),而不是

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)
这将给出预期的输出:

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