在博問上問了一個排列組合的問題,剛開始一直沒有人回答,后來終於等到一位用戶名為“開心的小草(https://home.cnblogs.com/u/kaixindexiaocao/)”來幫助我解決我問題。
他回答德很詳細,而且還貼圖給我,真的感到很溫暖很感動。
我把他的代碼重新整理了一遍發到博客里分享。問題和代碼內容如下:
有下面1個列表,列表中又嵌套不同長度的列表,想要輸出的結果是,把strLst[0][0]到strLst[4][1]按順序全部遍歷一遍,然后把元素拼接在一起輸出。
請問有什么辦法可以實現嗎?先謝謝各位大神了!
strLst = [['cmd1'],['opt1-1','opt1-2',''],['opt1-3'],['opt1-4',''],['opt1-5','']]
輸出結果:
cmd1 opt1-1 opt1-3 opt1-4 opt1-5
cmd1 opt1-1 opt1-3 opt1-4
cmd1 opt1-1 opt1-3 opt1-5
cmd1 opt1-1 opt1-3
cmd1 opt1-2 opt1-3 opt1-4 opt1-5
cmd1 opt1-2 opt1-3 opt1-4
cmd1 opt1-2 opt1-3 opt1-5
cmd1 opt1-2 opt1-3
cmd1 opt1-3 opt1-4 opt1-5
cmd1 opt1-3 opt1-4
cmd1 opt1-3 opt1-5
cmd1 opt1-3
代碼如下:
strLst = [['cmd1'],['opt1-1','opt1-2',''],['opt1-3'],['opt1-4',''],['opt1-5','']] a = [] L = [] n = [] for i in range(len(strLst)): a.append(strLst[i]) L.append(len(strLst[i])) n.append(0) sum = 1 for i in range(len(L)): sum = sum * L[i] count = 0 while count < sum: #運用滿位進一的辦法 for i in reversed(range(len(n))): if n[i] >= L[i]: n[i] = 0 if i != 0: n[i - 1] += 1 #輸出段 needoutput = '' for i in range(len(a)): if a[i][n[i]] != '': needoutput = needoutput + a[i][n[i]] + '\t' else: needoutput = needoutput + a[i][n[i]] needoutput = needoutput.expandtabs(1) print(needoutput) n[len(n) - 1] += 1 count += 1
博問原帖:https://q.cnblogs.com/q/109716/