首页 > 解决方案 > Why doesn't fusing two loops together produce the same result as a nested loop?

问题描述

(Using python 2)

I was suggested to fuse my two of my loops together to speed up my code that was taking way too long.

So instead of this:

for timestep in range(0,100): 
     for xn in xrange(0,npoints):
          for step in xrange(0,npoints):


               fx=somefunction[xn]+somefunction[step]

               print fx

I used this:

for timestep in xrange(0,100):
     for step, xn in itertools.product([0,npoints-1],[0,npoints-1]):


          fx=somefunction[xn]+somefunction[step]

          print fx

but I got two very different results when I printed out my function, fx.

For the nested loop (the first block of code), I got a list of 999 numbers (which was the correct length).

However, when I tried to merge the two loops together (second block of code), I only got four out of the 999 numbers I was supposed to get in my list.

Am I merging my for-loop wrong? Is there another way to merge a nested for loop together that will still help speed up my code?

标签: pythonfor-loopmergenested-loops

解决方案


你得到不同的结果,因为你没有使用相同的序列。你仍然需要xrange,作为product它的参数,而不是成对的端点。

for step, xn in itertools.product(xrange(0, npoints), repeat=2):

使用product([0,n_points-1], [0,n_points-1]),您只是迭代元组:(0,0)(0,n_points-1)(n_points-1,0)(n_points-1,n_points-1),而不是您想要的 O( n_points**2) 不同的元组。


推荐阅读