[Tutor] triple-nested for loop not working
Alan Gauld
alan.gauld at btinternet.com
Thu May 5 00:44:10 CEST 2011
"Spyros Charonis" <s.charonis at gmail.com> wrote
> motif_file = open('myfolder/pythonfiles/final motifs_11SGLOBULIN',
> 'r')
> align_file = open('myfolder/pythonfiles/11sglobulin.seqs', 'a+')
> finalmotif_seqs = []
> finalmotif_length = [] # store length of each motif
> finalmotif_annot = []
>
> finalmotifs = motif_file.readlines()
> seqalign = align_file.readlines()
NB. I've moved the lines to after the initialisation, but...
> for line in finalmotifs:
> finalmotif_seqs.append(line)
> mot_length = len(line)
> finalmotif_length.append(mot_length)
>
> for item in finalmotif_length:
> annotation = '~' * item
> finalmotif_annot.append(annotation)
This seems very verbose. Why not go directly to the tildes?
for line in finalmotifs:
finalmotof_seqs.append(line)
finalmotif_annot.append('~' * len(line))
You don't seem to use the list of lens for anything else?
> for line in seqalign:
> for i in len(finalmotif_seqs): # for item in
> finalmotif_seqs:
len() returns an integer not a sequence so you can't
iterate over it, you would need range(), but...
> for i in len(finalmotif_annot): # for item in
> finalmotif_annot:
> if finalmotif_seqs[i] in line: # if item in
> line:
> newline = line.replace(finalmotif_seqs[i],
> finalmotif_annot[i])
> #sys.stdout.write(newline) # => print the lines
> out on
> the shell
> align_file.writelines(newline)
You comments are better python than your code is!
with open(align_file) as seqalign:
for line in seqalign:
for seq in finalmotif_seqs:
for annot in finalmotif_annot:
line = line.replace(seq, annot) # +'\n'???
align_file.write(line)
> motif_file.close()
> align_file.close()
If you use 'with' you don't need these...
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list