Python|测试字符串是否包含列表中的元素
在使用Python进行 Web 开发期间,我们通常会遇到一个问题,即我们需要测试给定列表中的特定元素是否位于子字符串中。这种问题在机器学习领域也很常见。让我们讨论一些可以做到这一点的方法。
方法#1:使用列表推导
这个问题可以使用列表推导来解决,在这里,我们检查列表以及字符串元素是否可以找到匹配项,如果找到匹配项,则返回 true,并且 false 未使用条件语句。
Python3
# Python3 code to demonstrate
# checking if string contains list element
# using list comprehension
# initializing string
test_string = "There are 2 apples for 4 persons"
# initializing test list
test_list = ['apples', 'oranges']
# printing original string
print("The original string : " + test_string)
# printing original list
print("The original list : " + str(test_list))
# using list comprehension
# checking if string contains list element
res = [ele for ele in test_list if(ele in test_string)]
# print result
print("Does string contain any list element : " + str(bool(res)))
Python3
# Python3 code to demonstrate
# checking if string contains list element
# using list comprehension
# initializing string
test_string = "There are 2 apples for 4 persons"
# initializing test list
test_list = ['apples', 'oranges']
# printing original string
print("The original string : " + test_string)
# printing original list
print("The original list : " + str(test_list))
# using list comprehension
# checking if string contains list element
res = any(ele in test_string for ele in test_list)
# print result
print("Does string contain any list element : " + str(res))
输出 :
The original string : There are 2 apples for 4 persons
The original list : ['apples', 'oranges']
Does string contain any list element : True
方法 #2:使用 any()
使用任何函数都是最经典的方式,您可以通过它高效地执行此任务。此函数检查字符串中的匹配是否与列表中每个元素的匹配。
Python3
# Python3 code to demonstrate
# checking if string contains list element
# using list comprehension
# initializing string
test_string = "There are 2 apples for 4 persons"
# initializing test list
test_list = ['apples', 'oranges']
# printing original string
print("The original string : " + test_string)
# printing original list
print("The original list : " + str(test_list))
# using list comprehension
# checking if string contains list element
res = any(ele in test_string for ele in test_list)
# print result
print("Does string contain any list element : " + str(res))
输出 :
The original string : There are 2 apples for 4 persons
The original list : ['apples', 'oranges']
Does string contain any list element : True