验证一个列表的元素是在一个字符串
问题描述:
验证一个列表的元素是AA串验证一个列表的元素是在一个字符串
我的关键词列表:
check_list = ['aaa','bbb','ccc']
而且一组字符串:
test_string_1 = 'hellor world ccc'
test_string_2 = 'hellor world 2'
我想确认是否有任何列表的元素是字符串中
for key in check_list:
if key in test_string_1:
print 'True'
但
,而不是打印值返回TRUE或FALSE
所以我可以这样做:
if some_conditions or if_key_value_in_test_string:
do something
答
如果我理解正确的,你想要什么,你可以这样做:
def test(check_list, test_string)
for key in check_list:
if key in test_string:
return True
return False
或在一个单行中你可以做:
any([key in test_string for key in check_list])
或使用属TOR表达,这可能是有利的长列表,因为它会短路(也就是停在第一True
而不需要先建立完整的列表):
any(key in test_string for key in check_list)
答
使用内置函数
>>> check_list = ['aaa','bbb','ccc']
>>> test_string_1 = 'hellor world ccc'
>>> test_string_2 = 'hellor world 2'
>>> any([(element in test_string_1) for element in check_list])
True
>>> any([(element in test_string_2) for element in check_list])
False
>>>
Yeap,那就是我想要的。是否有必要定义一个函数?还是可以使用列表理解? –
@LuisRamonRamirezRodriguez:你可以使用'any([我在[[2,3],[4,5],[1,7]]])'中的i'。 – tom10