question on list comprehensions
Mustafa Demirhan
mustafademirhan at gmail.com
Fri Oct 15 13:36:30 EDT 2004
Why not just use while loops instead of for loops? You dont have to
create a new array each time you want a loop - you can simply use an
index integer.
i = 0
while i < 5000000:
res [0] = res [0] + i
i = i + 1
Takes less than 2 seconds on my laptop.
Darren Dale <dd55 at cornell.edu> wrote in message news:<ckm2up$cjv$1 at news01.cit.cornell.edu>...
> Hi,
>
> I need to replace the following loop with a list comprehension:
>
> res=[0]
> for i in arange(10000):
> res[0]=res[0]+i
>
> In practice, res is a complex 2D numarray. For this reason, the regular
> output of a list comprehension will not work: constructing a list of every
> intermediate result will result in huge hits in speed and memory.
>
> I saw this article at ASPN:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297
>
> def thislist():
> """Return a reference to the list object being constructed by the
> list comprehension from which this function is called. Raises an
> exception if called from anywhere else.
> """
> import sys
> d = sys._getframe(1).f_locals
> nestlevel = 1
> while '_[%d]' % nestlevel in d:
> nestlevel += 1
> return d['_[%d]' % (nestlevel - 1)].__self__
>
> Could the list comprehension include something like thislist().pop(0), to be
> called when len(thislist)>1? (I think this could work, but am having
> trouble with the syntax.) Or is there a better way to approach the problem?
>
> Thank you,
>
> Darren
More information about the Python-list
mailing list