On 03/18/2010 02:02 AM, Karjer Jdfjdf wrote: > I'm having problems with iterations and loops.. So I'm curious about the > best Python-way to do iterations of lists (in if, while etc statements) > and breaking of loops.
"Best" is a relative term to the current context of the problem. What is best for one case, might be worse for another. > I have a list of tuples with 2 values. I want to perform calculations on > all of these for each value in a range of values (e.g. 100 to 110). > > > list_of_tuples = [(90629, 4644), (90706, 4617), (90729, 4709)] > > #start value > n = 100 > #maximum value > nmax = 110 > > #First I create a list for the values > range_list = [] > while n < int(nmax+1): > range_list.append(n) > n = n + 1 "for i in xrange(n, nmax):" is a common idiom in python to do something a predetermined amount of time. Actually, all that code can be replaced with just "range_list = range(n, nmax)". Also, I think it is good if you can get used to counting with a half-open interval; though initially is a bit awkward, half-open counting is much less error prone. > print range_list > > > for i in range_list: > for t in list_of_tuples: > val1 = t[0] > val2 = t[1] > print "do stuff with\t" + str(val1) + '\t' + str(val2) + \ > '\tfor rangevalue\t' + str(i) > > But I think that the rangelist is not needed and it can be done better > (and faster for large quantities of data). I think it's better to have > somethng like the code below. But I'm having problems with breaking the > second loop and returning to the first loop. If I put in another > while-statement befor the for-statement it stops after 1 run and it has > to continue until the end of the range. I usually avoid preallocating large list to store results by using list-comprehension and generators. The interpreter would still have to allocate the list, but at least they're out of my immediate sight. Anyway, you should probably elaborate more about the problem you're having. What you've described up till now is "how I think the problem should be solved"; it is much more useful to describe "what the problem really is" so we can probably suggest a totally different approach to solve the problem. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor