[Tutor] Python Newbie: Lost in Loop

Kent Johnson kent37 at tds.net
Fri Apr 4 19:55:17 CEST 2008


yogi wrote:
> Hi all, 
>         I ´m a Python Newbie. Just 48 hrs into Python.
> I am  trying to parse a file which is tab spaced.

You're close...

> My Python code
>  #/bin/python
> import sys, csv, re
> 
> # This programme finds the SNPs from the range passed from
> the select option
> ## But first for fixed values.
> gen = 16
> rval0l = 6009890
> rval0u = 6009939
> rval1l = 0
> rval1u = 0
> types = (int, str, int, int)
> fis = csv.reader(open("divs.map", "rb"), delimiter='\t',
> quoting=csv.QUOTE_NONE) # csv splits columns and this file
> is tab spaced
> # Reading file line by line and using Regex to match the
> gene.
> for row in fis:
>         #if re.search("^[1-9]\-^[1-9]\:^[1-9]\-^[1-9]", row
> [3]):
>         if (str(gen) == str(row[0])):

row[0] is already a string so this could be
   if str(gen) == row[0]
or
   if gen == int(row[0])

>                 print 'Match for 16 found looking for SNPs
> in range between '+ str(rval0l),str(rval0u)+' '
>                 for row[2] in range (rval0l,rval0u):
>                         print row

This is confused. I think you want all the rows where row[3] (not 2) is 
between rval0l and rval0u? So just make this another condition:
   if rval0l <= int(row[3]) <= rval0u:
     print row

Aside to the list:
Did anyone else know that you can assign to a list element as the target 
of a for statement?

In [6]: row=range(3)
In [8]: for row[2] in range(5):
     print row
    ...:
    ...:
[0, 1, 0]
[0, 1, 1]
[0, 1, 2]
[0, 1, 3]
[0, 1, 4]

Color me surprised.

Kent


More information about the Tutor mailing list