看板 Python 關於我們 聯絡資訊
請問list的子集合如何求出,我想做的是投入一列表可以return其子集的函式 nums=[1,2,3] #這是想要的結果 [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]] #想法:每抽出1,2,3,幾個元素,便存成一個list def NS(list): S=[] j=len(list) for i in list: S.append([i]) while(j>=0): S.append(list[:j]) S.append(list[j:]) j-=1 return S print(NS(nums)) #這個結果是 [[1], [2], [3], [1, 2, 3], [], [1, 2], [3], [1], [2, 3], [], [1, 2, 3]] 可是我求不出[1, 3],先謝謝版大的回答。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.37.1 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1669450199.A.FDA.html
lycantrope: 原始code是把list從頭到尾切兩邊再append,並不是組合 11/26 16:55
lycantrope: 可以查一下itertools.combinations 11/26 16:56
genius091612: leetcode 78. Subsets 就是你要的 11/26 18:00
mantour: 想一下樹狀圖:第一層是“1”要放或不放,第二層是”2” 12/02 07:36
mantour: 要放或不放,... 12/02 07:36
mantour: 或是想成2進位的000到111,000對應[ ],111對應[1,2, 12/02 07:38
mantour: 3] 12/02 07:38