更快的构造数组数组的方法

时间:2015-07-05 07:22:15

标签: python

我有两个长列表xy包含大约1000个元素,其数字大小为~10^6。我正在使用列表推导构建1000x1000数组数组,我将其用作矩阵。

m = [[f(x[i], y[j]) for i in range(1000)] for j in range(1000)]

其中f(x,y)是一些返回x和y分数的函数。我们说Fraction[x,y]。我在列表xy中生成了0-10 ^ 6的1000个随机数。执行时间为15.8269999027秒。

是否有任何数据结构允许我在1s下构建此矩阵?后来我必须使用它来找到这个矩阵的LU分解(我必须为它编写代码)并且我没有任何可用的库。

1 个答案:

答案 0 :(得分:1)

运行时由函数主导,所以没有任何方法可以解决这个问题。我可以给你看一个例子:

import random
import time

def randlist():
  return [random.randint(0, 10**6) for x in xrange(1000)]

def f(x, y):
  return x / y

random.seed(0)
x = randlist()
y = randlist()

# The code we want to optimize
start = time.time()
m = [[f(x[i], y[j]) for i in range(1000)] for j in range(1000)]
end = time.time()
print end - start

# Measuring the function invocations without creating the matrix at all
start = time.time()
for i in xrange(1000):
  for j in xrange(1000):
    f(x[i], y[j]) 
end = time.time()
print end - start

在我的电脑上,创建矩阵需要0.24秒,而运行功能100万次需要0.21秒。所以无论你如何构建矩阵,你只能节省~0.03s。