简体   繁体   中英

Get all ordered combinations of list python

I'm trying to generate all n-item combinations of a list of numbers while maintaining numerical order. So for example, if the list were

[1,2,3,4]

The ordered combinations of length 3 would be:

[1,2,3]
[2,3,4]
[1,2,4]
[1,3,4]

To be clear, I have to maintain numerical order, so [1,4,2] would not be a desired outcome.

Is there a function that does this, or a fast algorithm that would get it done? The actual list is 111 and I will be choosing 100 items. Thanks.

Are you just looking for all the combinations of a given list of length n? If so you can just use combinations from itertools. Either way you'll probably want to go with itertools.

from itertools import combinations

numbers = [1,2,3,4]
for item in combinations(numbers, 3):
    print sorted(item)

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