• 【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]] + '	'
            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/

  • 相关阅读:
    Assembly Manifest 通俗简易手册
    CruiseControl服务器安装配置
    关于URL编码
    从A到Z来说说Web开发
    通过注册表查看 .NET Framework的版本信息
    云数据存在哪里?
    C#中你可能不知道的8件事(zz)
    用PBKDF2 或BCrypt 来存储密码
    C++编译器什么时候为我们自动生成拷贝构造函数?
    C#中你可能不知道的8件事(zz)
  • 原文地址:https://www.cnblogs.com/xiaomaolove/p/9678983.html
Copyright © 2020-2023  润新知