首页 > 解决方案 > 在 Python3 中修复 TypeError 后会出现另一种 TypeError

问题描述

抱歉,如果这是一个重复的问题 - 我对 Python 不太擅长,其他答案并没有真正帮助我。

我有一个 python 脚本:plink2treemix.py从命令行调用它,如下所示:

plink2treemix.py data.vcf.frq.strat.gz treemix.gz

这是脚本(它很长,但有两个区域导致了这个问题,我已经标记了):

#!/usr/bin/python

import sys, os, gzip

if len(sys.argv) < 3:
    print("plink2treemix.py [gzipped input file] [gzipped output file]")
    print("ERROR: improper command line")
    exit(1)
infile = gzip.open(sys.argv[1], "rb") 
outfile = gzip.open(sys.argv[2], "w")


pop2rs = dict()
rss = list()
rss2 = set()

line = infile.readline()
line = infile.readline()
while line:
    line = line.strip().split()
    rs = line[1]
    pop = line[2]
    mc = line[6]
    total = line[7]
    if rs not in rss2: 
        rss.append(rs)
    rss2.add(rs)
    if pop not in pop2rs: 
        pop2rs[pop] =  dict() #FIRST TYPE ERROR
    if pop2rs[pop] in (rs)==0:
        pop2rs[pop][rs] = " ".join([mc, total])
    line = infile.readline()
print("reached end of while loop")

pops = pop2rs.keys()
for pop in pops:
    print >> outfile, pop,
print(outfile, "")
print("printed outfile")

for rs in rss:
    for pop in pops:
        tmp = pop2rs[pop]['rs'].split #SECOND TYPE ERROR
        c1 = int(tmp[0])
        c2 = int(tmp[1])
        c3 = c2-c1
        print >> outfile, ",".join([str(c1), str(c3)]),
    print(outfile, "")
print("programme finished")

第一个TypeError是:

line 31, in <module>
    if pop2rs[pop] in (rs)==0:
TypeError: 'in <string>' requires string as left operand, not dict

我通过将dict()上面一行中的更改为str().

这会在后面的代码中产生不同的 TypeError:

    tmp = pop2rs[pop][rs]
TypeError: string indices must be integers, not str

我不确定如何修复,rs = line[1]从输入文件开始,已经是一个 int 值,文件的标题如下:

CHR           SNP     CLST   A1   A2      MAF    MAC  NCHROBS
  22   22:17049382        0    T    C        0      0        2 
  22   22:17049382        1    T    C        0      0        2 
  22   22:17049382        2    T    C        0      0        2 

我将不胜感激任何帮助!

标签: pythonpython-3.xterminal

解决方案


推荐阅读