哈士奇WWW
通过将所需的列表追加到新列表中使用简单迭代:lst = ['a', 'b', 'c', 'd', 'e']nlst = []for i in range(len(lst)): for y in lst[i:]: nlst.append(lst[:i] + list(y))for x in nlst: print(x)# ['a']# ['b']# ['c']# ['d']# ['e']# ['a', 'b']# ['a', 'c']# ['a', 'd']# ['a', 'e']# ['a', 'b', 'c']# ['a', 'b', 'd']# ['a', 'b', 'e']# ['a', 'b', 'c', 'd']# ['a', 'b', 'c', 'e']# ['a', 'b', 'c', 'd', 'e']
呼啦一阵风
使用itertools recipes 中的 powerset recipe ,您可以执行以下操作:from itertools import chain, combinationsdef powerset(iterable): s = list(iterable) it = chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) return map(list, (e for e in it if e))result = sorted(powerset(['a', 'b', 'c', 'd']), key=lambda x: (len(x), ''.join(x)))for s in result: print(s)输出['a']['b']['c']['d']['a', 'b']['a', 'c']['a', 'd']['b', 'c']['b', 'd']['c', 'd']['a', 'b', 'c']['a', 'b', 'd']['a', 'c', 'd']['b', 'c', 'd']['a', 'b', 'c', 'd']更新鉴于更新的要求,您可以执行以下操作:lst = ['a', 'b', 'c', 'd']length = len(lst)def patterns(l): for i in range(length): for c in l[i:]: yield l[:i] + [c]for pattern in sorted(patterns(lst), key=lambda x: (len(x), ''.join(x))): print(pattern)输出['a']['b']['c']['d']['a', 'b']['a', 'c']['a', 'd']['a', 'b', 'c']['a', 'b', 'd']['a', 'b', 'c', 'd']