Python 避免在多个项目的请求中使用 item = None

Python avoid item = None in a request of multiple items

我正在为网络数据库上的多个请求做一个循环,每次需要一个 geneId 来请求它到数据库。如果引用了 geneId,我可以将我获得的数据用于第二个数据库上的另一个请求。但是,如果未引用 geneId,它不会给我任何回报,而且会破坏我的功能。 所以我确定了 None 的可能性,但在这种情况下我得到了 :

TypeError: 'NoneType' object is not iterable.

这是我的代码的一部分 None :

def getNewID(oneGeneIdAtOnce):
url = "http:/blablabla"
try :
    cookieJar = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookieJar))
    opener.addheaders = getHeaders()
    resp = opener.open(url)
    data = urllib.parse.urlencode(getPost(oneGeneIdAtOnce))
    data = data.encode("UTF-8")
    resp = opener.open(url, data)
    respData = resp.read()
    jobValue = getJobValueFromCookie(cookieJar)
    downloadUrl = getUrlFromJobValue(jobValue)
    resp = opener.open(downloadUrl)
    respData = resp.read()          
    string = respData.decode("UTF-8")
    if not string:
        return None
    l = string.split("\n")
    lFinal = l[1].split("\t")       
    return lFinal[1]
except HTTPError as httpError:
    print("HERE     " + str(httpError))
except TypeError:
    None


def searchGoFromDico(dictionary):   
dicoGoForEachGroup = {}
for groupName in dico:
    taxonAndGene = dico[groupName]          
    listeAllGoForOneGroup = []      
    for taxon in taxonAndGene:          
        geneIds = taxonAndGene[taxon]           
        for geneId in geneIds:                      
            if geneId is not None:                                  
                listeGo = getGoID(getUniprotID(geneId))                                             
                listeAllGoForOneGroup.extend(listeGo)               
    dicoGoForEachGroup[groupName] = listeAllGoForOneGroup                                                   
return dicoGoForEachGroup

即使数据库的 geneId 之一为 None,是否可以让我的函数正常工作?感谢您即将到来的答复。

您可以在导致问题的代码周围使用 try/except 块。如果列表为空,运行 外层 for 循环的下一次迭代(未测试):

def searchGoFromDico(dictionary):
dicoGoForEachGroup = {}
for groupName in dico:
    taxonAndGene = dico[groupName]
    listeAllGoForOneGroup = []
    for taxon in taxonAndGene:
        geneIds = taxonAndGene[taxon]
        try:
            for geneId in geneIds:
                if geneId is not None:
                    listeGo = getGoID(getUniprotID(geneId))
                    listeAllGoForOneGroup.extend(listeGo)
        except TypeError:
            continue

    dicoGoForEachGroup[groupName] = listeAllGoForOneGroup
return dicoGoForEachGroup