简体   繁体   中英

How to find all combinations by picking at most n items from a unique list

Let say I have a unique list:

H_coordinates = [(0, 1), (0, 3), (1, 0), (1, 2), (2, 1), (2, 2)]

And a variable that represents the number of items from the list that I want at most :

num_of_H = 2

I tried:

all_H_combinations = itertools.combinations(H_coordinates, num_of_H) 

but when I print:

print('all_H_combinations:', all_H_combinations )

I get:

all_H_combinations: <itertools.combinations object at 0x0000021C1B4A5AE8>

What am I doing wrong? or maybe there is another way?

Just:

print('all_H_combinations:', [p for p in all_H_combinations])

Output:

all_H_combinations: [((0, 1), (0, 3)), ((0, 1), (1, 0)), ((0, 1), (1, 2)), ((0, 1), (2, 1)), ((0, 1), (2, 2)), ((0, 3), (1, 0)), ((0, 3), (1, 2)), ((0, 3), (2, 1)), ((0, 3), (2, 2)), ((1, 0), (1, 2)), ((1, 0), (2, 1)), ((1, 0), (2, 2)), ((1, 2), (2, 1)), ((1, 2), (2, 2)), ((2, 1), (2, 2))]

It's correct: itertools.combinations returns a generator - you need to loop over it to see what it generated.

Or convert it to a list (this may take a lot of time and waste memory if there are a lot of combinations):

all_H_combinations = list(itertools.combinations(H_coordinates, num_of_H))

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