不使用递归且不引入标准库,单纯用两个for循环即可得出一个list的所有子集
L = [1, 2, 3, 4]
List = [[]]
for i in range(len(L)): # 定长
for j in range(len(List)): # 变长
sub_List = List[j] + [L[i]]
if sub_List not in L:
List.append(sub_List)
print('List =', List)
主要思想:
变长的 List 中的所有元素将会被不断地重复遍历,直到遍历完定长的 L
当然,不进行条件判断也行:
L = [1, 2, 3, 1] List = [[]] for i in range(len(L)): # 定长 for j in range(len(List)): # 变长 List.append(List[j] + [L[i]]) print('List =', List)
最后,如果考虑到程序的效率问题,那么建议引入 python 标准库中的 itertools,然后调用 combinations 这个函数
这样可以更加高效地得到一个 list 的所有的子集
代码如下:
from itertools import combinations L = [1, 2, 3, 1] result_list = sum([list(map(list, combinations(L, i))) for i in range(len(L) + 1)], []) print('result_list =', result_list)