Leon Surrao
Leon Surrao

Reputation: 637

iteration and matching items in lists

Am trying to check if elements of a list match elements of another. But there is a slight twist to the problem.

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

Am trying to match the elements of alist to the blist, but only the area code part(in blist). Here is my current code:

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

The code works for the most part, except when there is a string matching the area code anywhere else in the list. It should only print:

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

but it ends up printing

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

as there is a '949' in the last phone number. Is there a way to fix this?

Upvotes: 1

Views: 35

Answers (1)

tobias_k
tobias_k

Reputation: 82899

You can use a regular expression to get the part within (...) and compare that part to 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]

Example:

>>> 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']

If you really really want to do it without regular expressions, you could, e.g., find the position of the ( and ) and thus get the slice from the string corresponding to the region code.

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]

However, I would strongly suggest to just take this as an opportunity for getting started with regular expressions. It's not all that hard, and definitely worth it!

Upvotes: 2

Related Questions