python - 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?
解决方案
你得到不同的结果,因为你没有使用相同的序列。你仍然需要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
) 不同的元组。
推荐阅读
- java - Jar 文件抛出异常
- r - 按R中的位置匹配具有不同起点的字符
- python - 100% 工作的 Python 装饰器 DB 连接器在 VS 代码中显示错误
- karate - 如何访问 JsonPath 数组结果的值(空手道断言)
- customization - Octobercms 如何设置分页器样式
- python - python(pytest)中的子进程问题(丢失正在写入文件的数据)
- javascript - 开发服务器返回错误代码:500 React Native
- android - 如何在 android 中比较 mycurrent 日期和 Quarterwise
- php - 如何使用 ajax 和 jquery 调用具有所需数据的端点?
- javascript - Javascript - 序列化数组以发送到控制器