python - Transform every two fields of rows into columns containing two rows -


i transform every 2 fields of rows columns containing 2 rows. , loop transformation each row

this input:

id  refpop001   altpop001   refpop002   altpop002   refpop003   altpop003 id1 6   274 2   93  5   95 id2 202 0   220 0   73  0 id3 166 159 0   173 114 90 

this desired output:

id  pop001  pop002  pop003 id1ref  6   2   5 id1alt  274 93  95 id2ref  202 220 73 id2alt  0   0   0 id3ref  166 0   114 id3alt  159 173 90 

header , id column indicated clarification , not required in output

given transforming tab delimited plain text in file , data size not changing, straightforward approach is:

lines=open('file_or_stream_name.txt','r').readlines();  newlines=[] newlines.append('\t'.join('id','pop001','pop002','pop003')) #header line line in lines[1:]:     elements=line.split('\t')     newline=[]     newline.append(elements[0]+'ref')     newline.extend(elements[1::2])     newlines.append('\t'.join(newline))      newline=[]     newline.append(elements[0]+'alt')     newline.extend(elements[2::2])     newlines.append('\t'.join(newline))  newtext='\n'.join(newlines) #or '\r\n'.join(...), if you're in windows 

Comments