如何按顺序排列组合输出字符串
问题:
希望按下述方式输出给定列表中的字符串:
[ ['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
解答:
要解决此问题,可以使用嵌套循环和满位进位方法:
a0 = strlst[0] a1 = strlst[1] a2 = strlst[2] a3 = strlst[3] a4 = strlst[4]
l0 = len(a0) l1 = len(a1) l2 = len(a2) l3 = len(a3) l4 = len(a4)
n0 = 0 n1 = 0 n2 = 0 n3 = 0 n4 = 0
sum = l0 * l1 * l2 * l3 * l4
count = 0 while count < sum: # 递增 n4,重置其他变量 n4 += 1 if n4 >= L4: n4 = 0 n3 += 1 if n3 >= L3: n3 = 0 n2 += 1 if n2 >= L2: n2 = 0 n1 += 1 if n1 >= L1: n1 = 0 n0 += 1 if n0 >= L0: n0 = 0 # 输出当前组合 output = "" if a0[n0] != '': output += a0[n0] + '\t' else: output += a0[n0] if a1[n1] != '': output += a1[n1] + '\t' else: output += a1[n1] if a2[n2] != '': output += a2[n2] + '\t' else: output += a2[n2] if a3[n3] != '': output += a3[n3] + '\t' else: output += a3[n3] if a4[n4] != '': output += a4[n4] output = output.expandtabs(7) print(output) count += 1
通过执行此代码,您可以生成所有可能的字符串组合并按顺序将其输出。
以上就是如何使用嵌套循环和满位进位方法输出字符串列表的所有排列组合?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号