Search code examples
pythonindexingiterationenumerate

Using index in Python to iterate through columns


I am trying to iterate through columns in a data file, to perform my task and then save the output to a file. I have almost 200 columns and unfortunately so far I can only get the required output by changing the column index manually (where ###). I have managed to get the index numbers that I want to use from my row names into a list (called x). I've been playing around with this but I am stuck as to how to make it iterate through these indices in the correct places. Below is what I have so far:

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

When I return x I get:

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

Using motif[x[1]] returns the correct names and columns, however this is the same as me putting the index in manually. Any help is appreciated!


Solution

  • Instead of:

    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
    

    you can iterate through x since x is a list of the column indices:

    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
    

    You can read more about for loops here.