[英]Check if string contains more than one element from array in Python
我在我的項目中使用正則表達式,並有一個這樣的數組:
myArray = [
r"right",
r"left",
r"front",
r"back"
]
現在我想檢查字符串,例如
message = "right left front back"
在這個數組中有多個匹配,我的目的是只有當只有一個單詞匹配其中一個數組時才有一個if。
我嘗試了很多東西,比如這個
if any(x in str for x in a):
但我從來沒有限量使用它。
你可以在這里使用sum
。 這里的技巧是True
在查找sum
計算為1
。 因此,您可以直接使用in
。
>>> sum(x in message for x in myArray)
4
>>> sum(x in message for x in myArray) == 1
False
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)
如果在message
找到myArray
中的至少一個字符串,則求值為True
。
sum(x in message for x in myArray) == 1
如果在message
找到myArray
一個字符串,則求值為True
。
如果您正在尋找最快的方法之一,請使用集合的交集:
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.