2016-08-10 68 views
0

我在使用python查找列表中的字符串的一部分時遇到了一個小問題。如何將字符串與列表中的「模式」分開

我從文件加載字符串和值是下列之一:(none, 1 from list, 2 from list, 3 from list or more...)

我需要根據字符串是否等於""不同的動作來執行,該字符串等於1 element from list,或者如果String是2個或更多元素。例如:

List = [ 'Aaron', 'Albert', 'Arcady', 'Leo', 'John' ... ] 
String = ""    #this is just example 
String = "Aaron"  #this is just example 
String = "AaronAlbert" #this is just example 
String = "LeoJohnAaron" #this is just example 

我創造了這樣的事情:

if String == "":   #this works well on Strings with 0 values 
    print "something" 
elif String in List:  #this works well on Strings with 1 value 
    print "something else" 
elif ...     #dont know what now 

最好的辦法是在此字符串從列表中拆分模式。我試圖:

String.Find(x) #failed. 

我試圖找到類似的帖子,但不能。

+0

你在做什麼樣的動作?我的意思是:如果文本是「LeoJohnAaron」,會發生什麼? 「LeoJohn」和「LeoJohnAaron」之間會有什麼聯繫,或者代碼是否完全不同? – Bakuriu

+0

如果文字是LeoJohnAaron應該 例如做2個動作: 從這個字符串 的另一個字符串。減去lenght和分離線 但它只是一個例子打印這些名字。 :) – degath

+0

「LeoJohnLeoLeo」會發生什麼?重複計數?訂單是否重要?一般的做法是使用正則表達式,例如're.findall('({})'.format('|'.join(map(re.escape,names))),text)'循環遍歷匹配,但根據我指出的一些因素,更簡單的解決方案可能會更好。 – Bakuriu

回答

0
if String == "":   #this works well on Strings with 0 values 
    print "something" 
elif String in List:  #this works well on Strings with 1 value 
    print "something else" 
elif len([1 for x in List if x in String]) == 2 
    ... 

這就是所謂的名單理解,它會經過列表,找到所有有共同的一個子手頭的字符串列表中的元素,然後返回的長度。

請注意,如果您有「Ann」和「Anna」這樣的名稱,則可能會出現一些問題,字符串中的名稱「Anna」會計入兩次。如果你需要一個解決方案來解決這個問題,我會建議拆分大寫字母,通過拆分大寫字母來明確區分單獨的名稱(如果你想我可以更新這個解決方案來演示如何用正則表達式)

+0

謝謝,它工作的很好,而且我沒有重複代碼:-) – degath

+1

哦,對不起,這是我的第一個問題,所以你需要原諒我:-) – degath

0

我認爲最簡單的方法是遍歷名稱列表,併爲每個名稱檢查它是否在您的字符串中。

for name in List: 
    if name in String: 
     print("do something here") 
0

所以,你想要找到某個字符串是否包含給定列表的任何成員。

遍歷列表,並檢查字符串是否包含當前項:

for data in List: 
    if data in String: 
     print("Found it!") 
相關問題