检查两个列表中的条件

时间:2017-03-20 03:06:16

标签: list python-3.x

我有2个列表,excludeNameexcludeZipCode,还有一个词典列表search_results。我需要根据几个条件从他们被复制到(search_copy)的列表中排除一些词典。排除名称的索引与排除的邮政编码的索引相同。目前我完全感到困惑,尽管我已经尝试了许多不同的方法来迭代它们并排除它们。我遇到的另一个问题是多次增加业务。

excludeName = ['Burger King', "McDonald's", 'KFC', 'Subway', 'Chic-fil-a', 'Wawa', 'Popeyes Chicken and Biscuits', 'Taco Bell', "Wendy's", "Arby's"]
excludeZip = ['12345', '54321', '45123', '39436', '67834', '89675', '01926', '28645', '27942', '27932']
while i < len(search_results):
        for business in search_results:
            for name in excludeName:
                occurrences = [h for h, g in enumerate(excludeName) if g == name]
                for index in occurrences:
                    if (business['name'] != excludeName[index]) and (business['location']['zip_code'] != excludeZip[index]):
                        search_copy.append(business)
        i += 1

这是一个示例词典:

{
    'location': {
        'zip_code': '12345'
    },
    'name': 'Burger King'
}

1 个答案:

答案 0 :(得分:1)

这首先复制您的业务实体列表,然后删除那些在excludedName / excludeZip对中有任何匹配项的实体。

search_copy=search_results[:]
for j in search_results:
    for i in range(0,len(excludeName)):
        if (j['name'] == excludeName[i]) and (j['location']['zip_code'] == excludeZip[i]):
            search_copy.remove(j)

理论上为了获得最佳性能,您希望首先迭代更大的列表,我认为这是企业列表