[Tutor] Python Newbie: Lost in Loop
Eric Walstad
eric at ericwalstad.com
Fri Apr 4 20:42:51 CEST 2008
Hi Yogi, welcome to Python!
yogi wrote:
...
> if (str(gen) == str(row[0])):
> print 'Match for 16 found
Is the conversion to string really necessary? Even if it is, do it once
for gen, when you define it:
gen = '16'
so you don't have to convert on every iteration of the loop. I think
you want gen to be a integer, though, because you later compare it to
other integers in your range().
...
> for row[2] in range (rval0l,rval0u):
> print row
I don't think this bit is doing what you think it is. For each
iteration you are assigning a value to the third element in the row list:
row[2] = 6009890
row[2] = 6009891
...
row[2] = 6009938
etc.
I don't think you want to loop over the range but instead want to check
to see if row[2] is between rval0l and rval0u. You can do that by using
if x in some_list
which will return true if x is a member of the list. range() will give
you the list of values to check against (but only create that list once
unless it changes on each row you are processing and in your code
example, it's not changing). Remember, it's easy and enlightening to
test code on the Python command line:
>>> rval0l = 6009890
>>> rval0u = 6009939
>>> range(rval0l,rval0u)
[6009890, 6009891, 6009892, 6009893, 6009894, 6009895, 6009896, 6009897,
6009898, 6009899, 6009900, 6009901, 6009902, 6009903, 6009904, 6009905,
6009906, 6009907, 6009908, 6009909, 6009910, 6009911, 6009912, 6009913,
6009914, 6009915, 6009916, 6009917, 6009918, 6009919, 6009920, 6009921,
6009922, 6009923, 6009924, 6009925, 6009926, 6009927, 6009928, 6009929,
6009930, 6009931, 6009932, 6009933, 6009934, 6009935, 6009936, 6009937,
6009938]
>>> my_range = range(rval0l,rval0u)
>>> 6009893 in my_range
True
>>> 5 in my_range
False
gen = 16
idx_snp = 2
my_range = range(rval0l,rval0u)
for row in file:
snp = int(row[idx_snp])
if snp == gen:
print 'Found %s' % gen
if snp in my_range:
print "Found match:", row
Eric.
PS, if your input file is as simple as your example, the csv module
isn't getting you much benefit/complexity:
for row in open("divs.map"):
fields = row.split('\t')
print fields
More information about the Tutor
mailing list