python中列表列表的匹配元素输出错误

时间:2017-08-14 17:28:33

标签: python list

我在python中有一个列表列表,其示例数据如下所示:

projContent

我所拥有的是我将两个参数传递给我的函数 - list_of_list = = [['AB2768', 'New York City', '25.0'], ['AB1789', 'San Francisco', '38.0'], ['AB6783', 'Chicago', '7.0'], ['AB2897', 'New York City', '30.0']] id。在我的函数中,我匹配如果参数匹配的bot然后返回第三个值,否则返回city。到目前为止,这是我的代码:

0

如果我def match_records(id, city): list_of_list = [['AB2768', 'New York City', '25.0'], ['AB1789', 'San Francisco', '38.0'], ['AB6783', 'Chicago', '7.0'],['AB2897', 'New York City', '30.0']] enrollment = '' print("searching for id- " + str(id)) print("searching for city- " + str(city)) for idnum, cityname, val in list_of_list: print(idnum + ', ' + cityname + ', ' + val) if str(idnum.strip()) != '' and str(id.lower().strip()) != str(idnum.lower().strip()) and str( city.lower().strip()) not in str(cityname.lower().strip()): print('either id is empty or id not found or city not found') flag = 1 else: print('Found a mactch') flag = 0 enrollment = val break return (flag == 0, enrollment) 理想情况下我应该print(match_records('AB2768', 'San Francisco')) FalseAB2768不在同一个列表中,但我得到San Francisco。实际上,如果两个输入中的任何一个输入正确,则返回True。我知道错误在True逻辑中的某处,但我无法猜测它是什么。这里有什么错误?

1 个答案:

答案 0 :(得分:1)

您可以在代码中使用“truthy”语句:

def match_records(id, city):
    list_of_list = [['AB2768', 'New York City', '25.0'], ['AB1789', 'San Francisco', '38.0'], ['AB6783', 'Chicago', '7.0'], ['AB2897', 'New York City', '30.0']]

    new_list = [i for i in list_of_list if id in i and any(city in b for b in i)]
    if new_list:
          return new_list[0][-1]
    else:
          return 0


print(match_records('AB2768', 'San Francisco'))

在此示例中,代码查找包含id和city的任何子列表。但是,如果在同一子列表中找不到两者,则子列表将不会添加到理解中的输入列表中。因此,如果未找到匹配项,则将创建一个空列表。在Python中,空列表的计算结果为False,因此返回其布尔值将给出False