为什么下面的If语句在Python中不起作用?

时间:2017-12-01 21:40:51

标签: python

import requests #for working with APIs
import json #for working with the output of the APIs
import pandas # for working with data frames and reading a csv
import os #for working with directories
import time #pause the loop for 1 second, so that our API call does not get timed out
import sqlite3 #because the API calls are expensive, once we have received information we store it in a sql lite db file, and we will generate the file from there



conn=sqlite3.connect("PhysicianSpecialty.db")
cur=conn.cursor()
cur.execute("SELECT distinct PhysicianNPI from PhysicianSpecialty")
IsPhysicianInDBSet=set(list(cur.fetchall()))
print(len(IsPhysicianInDBSet))


physicianlist=["1992952816","1255433801","1861704249"]

for physicianid in physicianlist:
    if str(physicianid) in IsPhysicianInDBSet:
        print("No Need of Api Call")
    else:
        print("Will need a API call")

SQLite数据库表有一个NPI列表及其专业。我正在将它变成一个集合,并且在迭代输入医师列表时想要检查我是否已经在本地拥有该信息,而不是进入API调用。在上面的例子中,只有else部分正在执行。我做错了什么?

2 个答案:

答案 0 :(得分:1)

列表中的元素是单例元组:

>>> import sqlite3
>>> conn=sqlite3.connect(':memory:')
>>> conn.execute('select "foo" union select "bar"').fetchall()
[('bar',), ('foo',)]
>>> 'foo' in _
False

您的抓取应该看起来更像这样:

result = [row[0] for row in cur]

或作为一组:

result = set(row[0] for row in cur)

答案 1 :(得分:0)

您的医生ID不是您认为的,或者您的医生名单不是,因为从根本上它是有效的。您需要在列表中添加一些打印语句,以确保它们符合您的预期。

physicianlist=["1992952816","1255433801","1861704249"]

>>> str(1992952816) in physicianlist
True