Reputation: 3
I am new to python and am trying to generate a list of all possible combinations of array elements. This is my attempt:
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]
But this is taking longer than I would like. Is there a faster way than what I have here? It looks like an itertools.combination possibility?
Upvotes: 0
Views: 85
Reputation: 860
Depending on how you want to use your list, you may or may not want to consider the use of generators so that you do not have to pay the cost of the computation up front.
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))
Running the above code gave me the following computations/run times. Note that itertools evaluated the generator.
Regular list comprehension/Regular loop: 3.8275507260113955
Itertools.product/Regular loop: 2.764477888995316
Regular list comprehension/Generator: 0.00015614699805155396
Itertools.product/Generator: 2.8045845669985283
Upvotes: 0
Reputation: 1173
this should get you the same results
list(itertools.product(Is, Js, Ks))
Upvotes: 1