2016-03-03 196 views
3

從陣列多個元素我使用正則表達式在我的項目,並且有一個這樣的數組:檢查字符串包含在Python

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

現在我要檢查,如果字符串,例如

message = "right left front back" 

有這個陣列中的一個以上的比賽,我在這裏的目的是有一個,如果是真實的,只有當只有一個詞相匹配的陣列中的一個。

我嘗試了很多東西,像這樣的

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

但我從來沒有使它與數量有限的工作。

+0

怎麼樣'匹配='[中如果x str中X爲X]。然後你可以用'len(matches)'檢查匹配的數量。 – zondo

+4

[Python:如何確定字符串中是否存在單詞列表]的可能重複(http://stackoverflow.com/questions/21718345/python-how-to-determine-if-a-list-of-words在字符串中存在) –

+2

@Michal Frystacky沒有遇到過,即使我之前查了很多,stackoverflow是如此巨大!謝謝 ! – ThaoD5

回答

3
matches = [a for a in myArray if a in myStr] 

現在檢查的matcheslen()

+1

太棒了!謝謝 – ThaoD5

3

您可以在這裏使用sum。這裏的技巧是True計算爲1,同時找到sum。因此,您可以直接使用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 
+0

謝謝,正是我所需要的,與if語句的例子,完美;-) – ThaoD5

+0

很高興成爲幫助。 –

2
any(x in message for x in myArray) 

則計算結果爲True如果至少一個myArray字符串中message被發現。

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

則計算結果爲True如果恰好myArray一個字符串中message被發現。

2

如果您正在尋找最快的方法來做到這一點使用的套十字路口之一:

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

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