从浮点数组构建列表的更快方法

时间:2016-03-03 14:46:25

标签: python numpy

我是python的新手,我正在尝试生成所有可能的数组元素组合的列表。这是我的尝试:

Ks = (np.arange(Low_Lim[2], (High_Lim[2]+1)) * grid_space + OFFSETS[2])

Js = (np.arange(Low_Lim[1], (High_Lim[1]+1)) * grid_space + OFFSETS[1])

Is = (np.arange(Low_Lim[0], (High_Lim[0]+1)) * grid_space + OFFSETS[0])

Points = [(a, b, c) for a in Is for b in Js for c in Ks]

但这比我想要的时间更长。有没有比我这里更快的方式?它看起来像itertools.combination的可能性?

2 个答案:

答案 0 :(得分:1)

这应该会得到相同的结果

list(itertools.product(Is, Js, Ks))

答案 1 :(得分:0)

根据您希望如何使用列表,您可能想也可能不想考虑使用生成器,这样您就不必预先支付计算成本。

*.min.css

运行上面的代码给了我以下计算/运行时间。请注意,itertools评估了生成器。

from timeit import Timer
setup_1 = """
Is = range(1000)
Js = range(300)
Ks = range(100)
"""
exec_1 = """
[(a, b, c) for a in Is for b in Js for c in Ks]
"""
exec_2 = """
list(itertools.product(Is, Js, Ks))
"""
t_1 = Timer(exec_1, setup_1)
print("Regular list comprehension/Regular loop: %r" % t_1.timeit(1))
t_2 = Timer(exec_2, setup_1)
print("Itertools.product/Regular loop: %r" % t_2.timeit(1))

setup_2 = """
Is = (i for i in range(1000))
Js = (i for i in range(300))
Ks = (i for i in range(100))
"""

t_3 = Timer(exec_1, setup_2)
print("Regular list comprehension/Generator: %r" % t_3.timeit(1))
t_4 = Timer(exec_2, setup_2)
print("Itertools.product/Generator: %r" % t_4.timeit(1))