【问题标题】:Using index in Python to iterate through columns在 Python 中使用索引来遍历列
【发布时间】:2014-06-20 15:43:12
【问题描述】:

我正在尝试遍历数据文件中的列,以执行我的任务,然后将输出保存到文件中。我有近 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]] 返回正确的名称和列,但这与我手动放入索引相同。任何帮助表示赞赏!

【问题讨论】:

    标签: python indexing iteration enumerate


    【解决方案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 循环here 的更多信息。

    【讨论】:

    • 谢谢你成功了!感谢链接,我什至没有考虑添加另一个 for 循环,因为当我添加另一个循环时,事情总是走下坡路,但感谢它很好用! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2021-09-01
    • 2016-03-04
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多