[英]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]
现在检查matches
的len()
。
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.