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

2024-10-01 09:30:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

代码

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']

Tags: 字符串代码nameintestforstringres
3条回答

你可以这么做

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

短期内,;简单的解决方案,参见@jussi nurminen使用列表理解的方法

如果你想坚持你原来的方法,它非常接近!您只需要附加test_string(这是正在检查的b中的当前元素),而不是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)

这将给出预期的输出:

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

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

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

相关问题 更多 >