比较两个列表的项目以找出所需的部分

时间:2019-07-09 22:03:06

标签: python python-3.x for-loop conditional-statements

有两个列表-一个包含list of states,另一个包含list of addresses。我正在尝试将each of the stateeach of the address进行比较,以查找是否存在匹配项。找到匹配项后,脚本应从地址中找出该部分。

这就是我所做的(工作一个):

state_list = ['AL', 'AK', 'AZ', 'AR', 'CO', 'CT', 'IL', 'MI']
addresses = ['Downers Grove IL 60515','Duarte CA 91010','Ann Arbor MI 48108']

for item in state_list:
    for address in addresses: 
        if item in address: 
            state = address
            print(state.split(" ")[-2])

输出:

IL
MI

我可以做一个单一的班轮方法,而不是这个笨拙的循环吗?

2 个答案:

答案 0 :(得分:2)

您也可以使用regex

import re

pattern = re.compile('|'.join(state_list))

[pattern.search(address).group(0) for address in addresses if pattern.search(address)]

['IL', 'MI']

或使用高阶函数

[m.group(0) for m in filter(None, map(pattern.search, addresses))]

['IL', 'MI']

答案 1 :(得分:1)

print([state for state in state_list
       if any(state in addr for addr in addresses)])

输出:

['IL', 'MI']