列表理解问题 [英] question on list comprehensions
问题描述
我需要用列表理解来替换以下循环:
res = [0]
for i in arange(10000):
res [0] = res [0] + i
实际上,res是一个复杂的2D numarray。出于这个原因,列表推导的常规
输出将不起作用:构建每个
中间结果的列表将导致速度和内存的大量命中。 />
我在ASPN看到这篇文章:
http://aspn.activestate.com/ASPN/Coo.../Recipe/204297
def thislist():
"""返回对由此函数调用的
列表解析构造的列表对象的引用。如果从其他地方调用,则会引发
异常。
""
import sys
d = sys._getframe(1).f_locals
nestlevel = 1
而''_ [%d]''%nestlevel in d:
nestlevel + = 1
返回d [''_ [%d]''%(nestlevel - 1)] .__ self__
列表理解能否包含类似于thislist()。pop(0)的东西,当len(thislist)> 1时要调用
? (我认为这可行,但是语法上有麻烦。)或者是否有更好的方法来解决问题?
谢谢,
Darren
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/Coo.../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
推荐答案
Darren Dale写道:
Darren Dale wrote:
我需要用列表理解来替换以下循环:
res = [0]
我在arange(10000)中:
res [0] = res [0] +我
I need to replace the following loop with a list comprehension:
res=[0]
for i in arange(10000):
res[0]=res[0]+i
为什么?
< / F>
why?
</F>
< br>
Darren Dale写道:
Darren Dale wrote:
我需要用列表理解来替换以下循环:
res = [0]
我在arange(10000):
res [0] = res [0] + i
res [0] =(10000 * (10000-1))/ 2.0 ;-)
在实践中,res是一个复杂的2D numarray。因此,列表推导的常规输出将不起作用:构建每个
中间结果的列表将导致速度和内存的大量命中。
Hi,
I need to replace the following loop with a list comprehension:
res=[0]
for i in arange(10000):
res[0]=res[0]+i
res[0] = (10000 * (10000-1))/2.0 ;-)
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.
为什么你需要*用listcomp替换for循环?你可以给b $ b提供更多关于你在复杂阵列上做些什么的细节吗?
Roberto
Why do you *need* to replace the for loop with a listcomp? Could you
give more details about what you''re doing with the complex array?
Roberto
Fredrik Lundh写道:
Fredrik Lundh wrote:
Darren Dale写道:
Darren Dale wrote:
我需要用列表理解来替换以下循环:
res = [0]
我在arange(10000):
res [0] = res [0] + i
I need to replace the following loop with a list comprehension:
res=[0]
for i in arange(10000):
res[0]=res[0]+i
为什么?
< / F>
why?
</F>
我在原帖中解释了原因......
I explained why in the original post...
这篇关于列表理解问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!