2015-07-10 60 views
1

我正在嘗試檢查列表中的元素是否與其他元素匹配。但是這個問題稍有轉折。迭代和匹配列表中的項目

alist = ['949', '714'] 
blist = ['(714)824-1234', '(419)312-8732', '(949)555-1234', '(661)949-2867'] 

我試圖將alist的元素與blist匹配,但只匹配區域代碼部分(blist)。這裏是我當前的代碼:

def match_area_codes(alist, blist): 
clist =[] 
for i in alist: 
    for j in blist: 
     if i in j: 
      clist.append(j) 
return clist 

代碼工作在大多數情況下,除非出現在列表中其他地方匹配區號的字符串。它應該只打印:

['(714)824-1234', '(949)555-1234'] 

,但它結束了打印

['(714)824-1234', '(949)555-1234', '(661)949-2867'] 

是有「949」在過去的電話號碼。有沒有辦法來解決這個問題?

回答

2

您可以使用regular expression獲取(...)中的零件,並將該零件與alist比較。

import re 
def match_area_codes(alist, blist): 
    p = re.compile(r"\((\d+)\)") 
    return [b for b in blist if p.search(b).group(1) in alist] 

例子:

>>> alist = set(['949', '714']) 
>>> blist = ['(714)824-1234', '(419)312-8732', '(949)555-1234', '(661)949-2867'] 
>>> match_area_codes(alist, blist) 
['(714)824-1234', '(949)555-1234'] 

如果你真的想這樣做,沒有正則表達式,你可以,例如,尋找()的位置,從而得到從區域碼對應的字符串中切片。

def match_area_codes(alist, blist): 
    find_code = lambda s: s[s.index("(") + 1 : s.index(")")] 
    return [b for b in blist if find_code(b) in alist] 

不過,我想強烈建議只是將此作爲入門用正則表達式的機會。這並不困難,絕對值得!

+0

使用're.compile'比將它放在列表理解中更好!在每次迭代中編譯正則表達式! – Kasramvd

+1

@Kasra是的,這就是爲什麼我使用're.compile'而不是將它放在列表理解中......或者你是什麼意思? –

+0

@ tobias_k..just so..is there a alternative way?我還沒有經過正則表達式。 –