Reputation: 457
I'm trying to get a itertools.combinations
to return a list of lists within a function, however my code returns a list of tuples...
array = list(combinations(a, m))
returns:
[(1, 2), (1, 3), (2, 3)]
I can manage to get the desired output by using a for loop:
array1 = []
for i in array:
array1.append(list(i))
return array1
returns:
[[1, 2], [1, 3], [2, 3]]
However I do not want to use a for loop within the function because there are other for loops, and I want to shorten for time complexity.
How can I get this list of lists from itertools.combinations
without using a for loop? Using a loop within list comprehension will also increase time. I cannot find the answer I want on SO posts or python websites.
Upvotes: 1
Views: 796
Reputation: 73498
The asymptotic complexity will always stay the same. You won't get around converting each combination to a list. You can do so lazily:
from itertools import combinations
def list_combs(iterable, k):
return map(list, combinations(iterable, k))
You can now use list_combs
as a drop-in replacement for combinations
, with the list conversion overhead only being applied lazily once the next combination is consumed.
for c in list_combs([1, 2, 3], 2):
print(c)
[1, 2]
[1, 3]
[2, 3]
Upvotes: 1