3 回答
TA贡献1799条经验 获得超6个赞
通过将所需的列表追加到新列表中使用简单迭代:
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']
TA贡献1802条经验 获得超6个赞
使用itertools recipes 中的 powerset recipe ,您可以执行以下操作:
from itertools import chain, combinations
def 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']
TA贡献1803条经验 获得超3个赞
尝试这个:
from itertools import combinations
a = ['a', 'b', 'c', 'd']
result = [list(combinations(a,i))for i in range(1,len(a)+1)]
并像这样打印:
for i in result:
print(*list(i), sep='\n')
添加回答
举报