在Python中使用索引遍历列

0 投票
1 回答
1527 浏览
提问于 2025-04-18 10:31

我正在尝试遍历一个数据文件中的列,以便完成我的任务,然后把结果保存到一个文件里。这个文件里大约有200列,但到目前为止,我只能通过手动更改列的索引(用###表示)来获得所需的输出。我已经成功地把我想用的索引号从行名中提取到一个列表里(叫做x)。我在这方面做了一些尝试,但现在卡住了,不知道怎么在正确的位置遍历这些索引。下面是我目前的代码:

with open('matrix.txt', 'r') as file:
    motif = file.readline().split()
    x = [i for i, j in enumerate(motif)]
    print x ### list of indices I want to use
    for column in (raw.strip().split() for raw in file):
        chr = column[0].split("_")
        coordinates = "\t".join(chr)
    name = motif[1] ### using column index
        print name
        for value in column[1]: ### using column index
            if value == "1":
                print coordinates
                out = open("%s.bed" %name, "a")
                out.write(str(coordinates)+"\n")
            elif value == "0":
                pass

当我返回x时,我得到:

x = [0, 1, 2, 3, 4,...]

使用motif[x[1]]可以返回正确的名称和列,但这和我手动输入索引是一样的。任何帮助都非常感谢!

1 个回答

1

与其这样:

name = motif[1] ### using column index
print name
for value in column[1]: ### using column index
    if value == "1":
        print coordinates
        out = open("%s.bed" %name, "a")
        out.write(str(coordinates)+"\n")
    elif value == "0":
        pass

你可以通过 x 来循环,因为 x 是一个包含列索引的列表:

for index in x:
    name = motif[index]
    print name
    for value in column[index]:
        if value == "1":
            print coordinates
            out = open("%s.bed" %name, "a")
            out.write(str(coordinates)+"\n")
        elif value == "0":
            pass

你可以在 这里 了解更多关于 for 循环的内容。

撰写回答