question on list comprehensions
Darren Dale
dd55 at cornell.edu
Thu Oct 14 10:36:51 EDT 2004
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