嵌套for循环获取正确的ord

2024-04-20 02:48:12 发布

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

在执行嵌套for循环时,我很难理解如何获得正确的输出顺序。你知道吗

我有一个整数列表:

[7, 9, 12]

和一个包含DNA序列数据行的.txt文件。你知道吗

>Ind1 AACTCAGCTCACG
>Ind2 GTCATCGCTACGA 
>Ind3 CTTCAAACTGACT

我试图创建一个嵌套for循环,它接受第一个整数(7),遍历文本行,并在每行的位置7处打印字符。然后取下一个整数,在每行的位置9处打印每个字符。你知道吗

with (Input) as getletter:
    for line in getletter:
        if line [0] == ">":

            for pos in position:
                snp = line[pos]
                print line[pos], str(pos)

当我运行上述代码时,我得到了所需的数据,但顺序不对,如下所示:

A  7
T  9
G  12
T  7
A  9
G  12
T  7
C  9
A  12

我想要的是:

A  7
T  7
T  7
T  9
A  9
C  9
G  12
G  12
A  12

我怀疑这个问题可以通过改变代码的缩进来解决,但是我不能把它弄对。你知道吗

----编辑----

我试图交换两个循环,但我显然没有得到更大的图片,这给了我同样的(错误的)结果如上所述。你知道吗

with (Input) as getsnps:
    for line in getsnps:
        if line[0] == ">":
            hit = line
        for pos in position:
                print hit[pos], pos

Tags: 数据inposforinputif顺序as
1条回答
网友
1楼 · 发布于 2024-04-20 02:48:12

尝试回答:

with (Input) as getletter:
    lines=[x.strip() for x in getLetter.readlines() if x.startswith('>') ]
    for pos in position:
        for line in lines:
            snp = line[pos]
            print ("%s\t%s" % (pos,snp))

文件被读取并缓存到数组中(行,丢弃不以>开头的文件) 然后我们在位置上迭代,然后是行,并打印出预期的结果。你知道吗

请注意,你应该检查你的偏移量不大于你的线。你知道吗

没有列表理解的替代方法(会占用更多的内存,特别是如果您有很多无用的行(即不以“>;”开头)

with (Input) as getletter:       
    lines=getLetter.readlines()
    for pos in position:
        for line in lines:
            if line.startswith('>'):
                 snp = line[pos]
                 print ("%s\t%s" % (pos,snp))

另一个存储的替代方案(假设位置小,输入大)

with (Input) as getletter:
    storage=dict()
    for p in positions:
        storage[p]=[]
    for line in getLetter:
        for p in positions:
            storage[p]+=[line[pos]]
for (k,v) in storage.iteritems():
    print ("%s -> %s" % (k, ",".join(v))

如果positions包含的值大于行的大小,则使用line[p]将触发异常(IndexError)。你要么抓住它,要么测试它

try:
    a=line[pos]
except IndexError:
    a='X'

if pos>len(line):
   a='X'
else:
   a=line[pos]

相关问题 更多 >