如何修复这个程序中的类型错误(列表索引必须是整数,而不是str)?

2024-10-01 13:26:45 发布

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

在我使用的一个程序中,当我试图从dict type数据中挖掘/解析一个值时,我得到了一个TypeError。在

下面是python程序的简短部分:

for c in results:
        print('value of c : ', c, type(c)) # what I added to see the issue with dict data
        for ci, lr in c['chain_info'].iteritems():
            outfile = open(lr.output_file, 'a')
            write = outfile.write

            if lr.number_vcf_lines > 0:
                write(CHAIN_STRING.format(CHAIN_STRING,
                            from_chr=c['chrom'], from_length=lr.chromosome_length,
                            from_start=0, from_end=lr.chromosome_length,
                            to_chr=c['chrom'], to_length=lr.end_length,
                            to_start=0, to_end=lr.sums[0] + lr.last_fragment_size + lr.sums[2], id=c['chrom']))
                write("\n")

完整回溯错误消息

^{pr2}$

文件的github位置:https://github.com/churchill-lab/g2gtools/blob/master/g2gtools/vcf2chain.py

似乎线路有问题:

from_chr=c['chrom'], from_length=lr.chromosome_length,

而且,Chain_string是作者创建的:

CHAIN_STRING = "chain 1000 {from_chr} {from_length} + {from_start} {from_end} " + "{to_chr} {to_length} + {to_start} {to_end} {id}"

我试图打印dict的值(通过添加print语句)来查看问题所在。在

print('value of c : ', c, type(c)) # gave me
('value of c : ', {'chrom': '1', 'stats': OrderedDict([('ACCEPTED', 0)]), 'chain_info': {'right': <g2gtools.vcf2chain.VCFtoChainInfo object at 0x7fe9de396dd0>, 'left': <g2gtools.vcf2chain.VCFtoChainInfo object at 0x7fe9d9252d50>}}, <type 'dict'>)

那么,这里有什么问题? 这个数据/程序有什么问题??在


Tags: tofrom程序valuetypestartlengthdict
2条回答

在你的评论中,你说c是一个字符串,那么 from_chr=c['chrom']不起作用,因为不能给字符串一个索引。在

In [3]: c = 'my string'

In [4]: c['chrom']
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-4-a201470ce4c5> in <module>()
  > 1 c['chrom']

TypeError: string indices must be integers

您的错误消息显示list indices must be integers, not str。我想c是一个列表。在这两种情况下,都不能给c一个字符串作为索引。在

问题是,在for循环中,variable c以列表形式返回:

for c in lr.chain_entries:
   write("\t".join(map(str, c)))
   write("\n") 

它在读取另一行时返回c作为列表。我不得不挖掘出c['chrom'],希望它是dict type。但是,这个变量被forloop改变了,引起了所有的麻烦。在

相关问题 更多 >