Work with combination object in python

>>> import itertools >>> n = [1,2,3,4] >>> combObj = itertools.combinations(n,3) >>> >>> combObj <itertools.combinations object at 0x00000000028C91D8> >>> >>> list(combObj) [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] >>> >>> for i in list(combObj): #This prints nothing ... print(i) ... 
  • How can I iterate through combObj?

  • How can I convert [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
    for image [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

+4
source share
3 answers

After repeating the itertools.combinations object itertools.combinations it has been used, and you cannot repeat it a second time.

If you need to reuse it, the correct way is to make it list or tuple as you did. All you have to do is give it a name (assign it to a variable) so that it obscures.

 combList = list(combObject) # Don't iterate over it before you do this! 

If you want to iterate over it only once, you just don't call list on it at all:

 for i in combObj: # Don't call `list` on it before you do this! print(i) 

Side note. The standard way to name object instances / normal variables would be comb_obj , not combObj . See PEP-8 for details.

To convert the internal tuple to list s, use list comprehension and the built-in list() :

 comb_list = [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] comb_list = [list(item) for item in comb_list] 
+7
source

To convert to a list of lists, you can do:

 [list(item) for item in combObj] 
0
source
Generators

good because they do not use a lot of memory. If you use it a lot and have memory, save it as a tuple instead of a generator.

Otherwise, I often make a function to return a generator every time I want to use it:

 >>> def get_combObj(): ... return itertools.combinations(n,3) ... >>> for i in get_combObj(): ... print list(i) ... [1, 2, 3] [1, 2, 4] [1, 3, 4] [2, 3, 4] 

(you can call get_combObj () as much as you want)

0
source

All Articles