def powerSet(L):
return [[]] if not L else [c for p in powerSet(L[1:]) for c in (p,L[:1]+p)]
x = ['a','b','c']
y = [",".join(s) or "ø" for s in powerSet(x)]
print(y)
['ø', 'a', 'b', 'a,b', 'c', 'a,c', 'b,c', 'a,b,c']
您也可以在迭代函数中直接执行此操作,该函数扩展列表中每个字母的所有先前组合:
def allCombos(L):
result = [""]
for c in L:
result.extend([f"{r},{c}" if r else c for r in result])
result[0] = "ø"
return result
print(allCombos(x))
['ø', 'a', 'b', 'a,b', 'c', 'a,c', 'b,c', 'a,b,c']
尽管这比itertools的效率要低得多,但如果不允许使用库,可以使用递归函数生成幂集,并在列表中使用join()组装字符串:
您也可以在迭代函数中直接执行此操作,该函数扩展列表中每个字母的所有先前组合:
相关问题 更多 >
编程相关推荐