Python avoid item=None在多个项的请求中

2024-09-25 12:32:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我对一个web数据库上的多个请求执行一个循环,每次需要一个geneId才能将其请求到数据库。如果引用了geneId,我就可以将获得的数据用于第二个数据库上的另一个请求。但是如果geneId没有被引用,它就不会给我任何回报,它会破坏我的功能。 所以我决定不可能,但这次我得到:

TypeError: 'NoneType' object is not iterable.

以下是我的代码的一部分,没有:

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对于数据库来说是空的?谢谢你接下来的回答


Tags: none数据库urldatastringreturnnotopen
1条回答
网友
1楼 · 发布于 2024-09-25 12:32:35

您可以在引起问题的代码周围使用try/except块。如果列表为空,则运行outer 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

相关问题 更多 >