Python: Generating all ordered combinations of a list

后端 未结 2 1324
春和景丽
春和景丽 2020-12-20 14:39

I\'m using Python 2.7.

I\'m having a list, and I want all possible ordered combinations.

import itertools
stuff = [\"a\",\"b\",\"c\", \"d\"]
for L in         


        
2条回答
  •  情书的邮戳
    2020-12-20 15:04

    I think you mean in continuous order by "in correct order", in this case you just need use two pointers to iterator over stuff:

    stuff = ["a","b","c", "d"]
    # sort stuff here if it's not sorted
    
    result = []
    for i in xrange(len(stuff)):
        for j in xrange(i+1, len(stuff)+1):
            result.append(stuff[i:j])
    
    # sort the result by length, maybe you don't need it
    result = sorted(result, key=len)
    
    for r in result:
        print ' '.join(r)
    

提交回复
热议问题