ipdb输出和Python interp之间的差异

2024-04-27 21:58:35 发布

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

下面是我的python脚本报告的错误:

TypeError                                 Traceback (most recent call last)
/home/jhourani/openbel-contributions/resource_generator/change_log.py in <module>()
     37         for k, v in namespaces.items():
     38             #ipdb.set_trace()

---> 39             if v[0]:
     40                 v[1].append(token)
     41 

TypeError: 'bool' object is not subscriptable

好吧,我想那很好。但是当我在ipdb中进一步检查这个元素时,结果是:

>>> v
(False, [])
>>> type(v)
<class 'tuple'>
>>> v[0]
False
>>> if v[0]:
...     print('true')
... else:
...     print('false')
... 
false
>>> 

条件测试在ipdb中工作,但是当我运行脚本时,解释器似乎将v视为一个布尔值,而不是一个当然是可下标的元组。1为什么?2为什么两者有区别?你知道吗

以下是我编写的代码块:

old_entrez = []
old_hgnc = []
old_mgi = []
old_rgd = []
old_sp = []
old_affy = []
# iterate over the urls to the .belns files
for url in parser.parse():
    namespaces = { 'entrez' : (False, old_entrez), 'hgnc' : (False, old_hgnc),
                   'mgi' : (False, old_mgi), 'rgd' : (False, old_rgd),
                   'swissprot' : (False, old_sp), 'affy' : (False, old_affy) }
    open_url = urllib.request.urlopen(url)
    for ns in namespaces.keys():
        if ns in open_url.url:
            namespaces[ns] = True
    marker = False
    for u in open_url:
        # skip all lines from [Values] up
        if '[Values]' in str(u):
            marker = True
            continue
        if marker is False:
            continue
        # we are into namespace pairs with '|' delimiter
        tokenized = str(u).split('|')
        token = tokenized[0]
        for k, v in namespaces.items():
            ipdb.set_trace()
            if v[0]:
                v[1].append(token)

Tags: intokenfalseurlforifentrezopen
1条回答
网友
1楼 · 发布于 2024-04-27 21:58:35

您正在检查第一次迭代,它工作正常。你知道吗

异常稍后发生。进一步遍历循环,因为在某个时刻,您将遇到一个名称空间键,该键的值已设置为True而不是一个布尔元组和一个列表)。你知道吗

为什么?因为在前面的代码中,您会:

for ns in namespaces.keys():
    if ns in open_url.url:
        namespaces[ns] = True

请注意= True;您可能想将其设置为:

namespaces[ns] = (True, namespaces[ns][1])

请注意,要循环字典的键,可以直接执行以下操作:

for ns in namespaces:

并为自己保存一个属性查找、一个函数调用和一个全新列表对象的创建。你知道吗

相关问题 更多 >