简体   繁体   中英

How to get itertools combinations as list of lists without for loop

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM