Large Loop Nest Design, Anyway To Improve Speed?
I want to loop through a list and check all the possible combinations in it. Currently, I'm using a series of nested for loops, and obviously I'm not ecstatic with the speed using
Solution 1:
It looks like you want to cover all combinations of one item picked from list1
, then two each from list2
- list5
. If correct, you can certainly make things more efficient:
from itertools import chain, combinations, product
for comb in product(combinations(list1, 1),
combinations(list2, 2),
combinations(list3, 2), ...):
Each comb
will be in the form ((l1,), (l2, l2), (l3, l3), (l4, l4), (l5, l5))
, but you can flatten this out using chain.from_iterable
:
comb = list(chain.from_iterable(comb))
To get [l1, l2, l2, l3, l3, l4, l4, l5, l5]
.
For a neatness improvement if not actual efficiency, you can define the lists to use and how many items to pick from each up front:
lists = [(list1, 1), (list2, 2), (list3, 2), (list4, 2), (list5, 2)]
forcombinproduct(*(combinations(l, n) forl, n in lists)):
Post a Comment for "Large Loop Nest Design, Anyway To Improve Speed?"