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」在過去的電話號碼。有沒有辦法來解決這個問題?
使用're.compile'比將它放在列表理解中更好!在每次迭代中編譯正則表達式! – Kasramvd
@Kasra是的,這就是爲什麼我使用're.compile'而不是將它放在列表理解中......或者你是什麼意思? –
@ tobias_k..just so..is there a alternative way?我還沒有經過正則表達式。 –