【python】按顺序排列组合输出字符串


在博问上问了一个排列组合的问题,刚开始一直没有人回答,后来终于等到一位用户名为“开心的小草(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/


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM