Python beginner here.
I am iterating through a text file, column by column.
for line in Input:
line = line.rstrip()
fields = line.split("\t")
for col in fields[5:]:
How would I keep track of which column I am in as I iterate through the columns? I want to print the current relevant column in the output so when I have my results I know which column the results refer to.
It seems like something for which there is an obvious answer, but I don’t know it!
Thanks in advance for the help. I find the helpfulness of people here overwhelming.
some input/output examples:
lines from input file :
chr20 1032 . A 1/1 1/1 1/1 0/1 0/0
chr20 1326 . T 1/1 1/1 1/1 0/1 0/0
chr20 1388 . C 0/0 1/1 ./. 0/1 0/0
Then I go through these lines looking at column 5 eg 1/1, 1/1, 0/0 and calculating some output statistics. My output file contains the statistics for every x number of rows calculated using column 5.
I’d like my output file to also include the results from column 6, 7 etc and for the rows in the output file to tell me which column the data was calculated from. In essence to save me rerunning the script seperately for each column.
output example:
5 chr1 230344070 231345012 1000942 200720 66560 119841 7160 5.63775088385 94.3622491161
5 chr1 231345012 232345029 1000017 167920 55040 106160 3360 3.06793279766 96.9320672023
5 chr1 232345029 233345195 1000166 179280 64841 96079 9180 8.72134449311 91.2786555069
With the first column here referring the fact it was calculated based on the values in column 5
for index, col in enumerate(fields[5:]):
Best,
Rubal
You could try something like this
enumerate() will generate an index value for you, by default it starts with 0 unless a starting value is specified as 2nd parameter to enumerate() as shown above with 5.
Variable
iwill start with the value 5 and allow you to track the current column you are working on andcol(as before) the value of the field in that column.Alternatively, just for convenience and easier modification, you could use a variable:
— UPDATE in reply to comments below:
I am still not quite sure I understand your comment, but if the loop you posted is inside a bigger loop you could to keep track of your current columns like this:
Posting some simple input/output examples would help if your code is too big to post. Hard to really know how to help without more information. I hope this is helpful.