如何加速python循环 [英] How to speed up python loop

查看:69
本文介绍了如何加速python循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了几个网站上的几个讨论,但没有一个给我解决方案.这段代码运行时间超过 5 秒:

I had a look at several dicussions on several sites and none of them gave me a solution. This piece of code takes more than 5 seconds to run :

for i in xrange(100000000):
  pass

我正在处理一个整数优化问题,我必须使用 O(n log n) 算法 O(n²/4) 算法,其中 n 代表所有矩阵的项,即,在以下代码中,n * m = 10000.因此,对于具有 10000 个元素的矩阵 100 * 100,将导致近 25000000 次迭代.......它的代码可以总结如下:

I'm working on an integer optimization problem and I have to use an O(n log n) algorithm edit : an O(n²/4) algorithm, where n stands for all the matrix' items, ie, in the following code, n * m = 10000. So, for a matrix 100 * 100 with 10000 elements, it will result in nearly 25000000 iterations .... Its code can be summed up like this :

m = 100
n = 100
for i in xrange(m):
  for j in xrange(n):
    for i2 in xrange(i + 1, m):
      for j2 in xrange(j + 1, n):
        if myarray[i][j] == myarray[i2][j2] and myarray[i2][j] == myarray[i][j2]:
          return [i, j], [i2, j2]

我应该放弃 Python 并回到 Java 或 C 吗?

Should I give up with Python and go back to Java or to C ?

我使用 Python 2.7,但 Psyco 不可用.PyPy 不支持开箱即用的 Tkinter,我正在使用 Tkinter.

I work with Python 2.7 and Psyco isn't available. PyPy doesn't support Tkinter out of the box and I'm using Tkinter.

那么,他们会提高循环速度吗?还有其他解决方案吗?

So, would they improve the looping speed ? Are there other solutions ?

推荐答案

不是最漂亮的编码风格,但绝望的时代需要绝望的编码.尝试将嵌套的嵌套循环变成一个大的生成器表达式:

Not the prettiest coding style, but desperate times call for desperate coding. Try turning your nested nested loops into one big generator expression:

try:
    i,j,i2,j2 = ((i,j,i2,j2)
        for i in xrange(m)
          for j in xrange(n)
            for i2 in xrange(i + 1, m)
              for j2 in xrange(j + 1, n)
                if myarray[i][j] == myarray[i2][j2] and 
                    myarray[i2][j] == myarray[i][j2]).next()
    return [i,j],[i2,j2]
except StopIteration:
    return None

更新为使用内置nextproduct,以及Py3 range 而不是xrange:

Updated to use builtins next and product, and Py3 range instead of xrange:

from itertools import product
match = next(((i,j,i2,j2)
    for i, j in product(range(m), range(n))
        for i2, j2 in product(range(i+1, m), range(j+1, n))
            if myarray[i][j] == myarray[i2][j2] and 
                myarray[i2][j] == myarray[i][j2]), None)
if match is not None:
    i,j,i2,j2 = match
    return [i,j],[i2,j2]
else:
    return None

这篇关于如何加速python循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆