简体   繁体   English

检查字符串是否包含Python中数组中的多个元素

[英]Check if string contains more than one element from array in Python

I'm using regular expression in my project, and have an array like this : 我在我的项目中使用正则表达式,并有一个这样的数组:

myArray = [
    r"right",
    r"left",
    r"front",
    r"back"
]

Now I want to check if the string, for example 现在我想检查字符串,例如

message = "right left front back"

has more than one match in this array, my purpose here is to have an if being true only if there is only one word matching one of the array. 在这个数组中有多个匹配,我的目的是只有当只有一个单词匹配其中一个数组时才有一个if。

I tried a lot of things, like this one 我尝试了很多东西,比如这个

if any(x in str for x in a):

but I never make it work with a limited amount. 但我从来没有限量使用它。

You can use sum here. 你可以在这里使用sum The trick here is that True is calculated as 1 while finding the sum . 这里的技巧是True在查找sum计算为1 Hence you can utilize the in directly. 因此,您可以直接使用in

>>> sum(x in message for x in myArray)
4
>>> sum(x in message for x in myArray) == 1
False

if clause can look like if子句看起来像

>>> if(sum(x in message for x in myArray) == 1):
...     print("Only one match")
... else:
...     print("Many matches")
... 
Many matches
matches = [a for a in myArray if a in myStr]

现在检查matcheslen()

any(x in message for x in myArray)

Evaluates to True if at least one string in myArray is found in message . 如果在message找到myArray 中的至少一个字符串,则求值为True

sum(x in message for x in myArray) == 1

Evaluates to True if exactly one string in myArray is found in message . 如果在message找到myArray 一个字符串,则求值为True

If you are looking for one of the fastest ways to do it use intersections of sets: 如果您正在寻找最快的方法之一,请使用集合的交集:

mySet  = set(['right', 'left', 'front', 'back'])
message = 'right up down left'

if len(mySet & set(message.split())) > 1:
    print('YES')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查字符串是否在python中包含一个或多个列表值 - Check if a string contains one or more of list values in python 从具有多个字符串元素的数组中提取数字 - Extract numbers from an Array which has more than one string element 具有多个元素的数组的真值是模棱两可的错误? Python - The truth value of an array with more than one element is ambiguous error? python 具有多个元素的数组的真值是模棱两可的Python错误 - The truth value of an array with more than one element is ambiguous Python error “具有多个元素的数组的真值不明确”错误 [Python] - "The truth value of an array with more than one element is ambiguous" error [Python] python 中的“具有多个元素的数组的真值不明确” - “The truth value of an array with more than one element is ambiguous” in python 如何检查字符串是否包含 Python 中列表中的元素 - How to check if a string contains an element from a list in Python Python-检查字符串是否包含列表中的任何元素 - Python - check if string contains any element from a list 如何检查字符串是否包含 Python 列表中的任何 3 个元素 - How to check if a string contains any 3 element from a list in Python 如何检查数组中的元素是否包含列表 Python 中的任何值 - How to check if element in array contains any values from a list Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM