我需要检查一个字符串是否存在于一组较大的字符串中,以及它是否存在,以便将包含它的字符串添加到另一个列表中。我有检查状态的代码,它正常工作,但由于我的实现,它无法添加字符串
代码
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']
你可以这么做
短期内,;简单的解决方案,参见@jussi nurminen使用列表理解的方法
如果你想坚持你原来的方法,它非常接近!您只需要附加
test_string
(这是正在检查的b
中的当前元素),而不是item
这将给出预期的输出:
下面是我应该做的一个代码,如果列表非常大,则使用多进程
相关问题 更多 >
编程相关推荐