python 生成list的全部的子集 (不使用遞歸且不引入標準庫)

不使用遞歸且不引入標準庫,單純用兩個for循環便可得出一個list的全部子集python

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)

主要思想:app

將上一個 List 中的元素拿出來和當前的 L 中的元素進行拼接,若此拼接的一個 sub_List 不在 List 中,那麼就將 sub_List 添加進入 List 中函數

 

 

固然,不進行條件判斷也行:spa

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 這個函數code

這樣能夠更加高效地獲得一個 list 的全部沒有重複元素的子集blog

代碼以下:遞歸

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)
相關文章
相關標籤/搜索