【发布时间】:2018-05-23 03:19:43
【问题描述】:
我正在尝试编写一个程序来打印两到四个字符之间所有可能的字母组合。我现在拥有的程序运行良好,但实现远非理想。这就是现在的样子:
# make a list that contains ascii characters A to z
ascii = list(range(65, 123))
del ascii[91 - 65 : 97 - 65] # values 91-97 aren't letters
for c1, c2 in product(ascii, repeat=2):
word = chr(c1) + chr(c2)
print(word)
for c1, c2, c3 in product(ascii, repeat=3):
word = chr(c1) + chr(c2) + chr(c3)
print(word)
for c1, c2, c3, c4 in product(ascii, repeat=4):
word = chr(c1) + chr(c2) + chr(c3) + chr(c4)
print(word)
我宁愿有以下精神的东西。请原谅我下面的代码是完全错误的,我试图传达我认为会更好的实现的精神。
iterationvars = [c1, c2, c3, c4]
for i in range(2,5):
for iterationvars[0:i] in product(ascii, repeat=i):
word = ??
print(word)
所以我有两个问题:
1) 如何在“母循环”的每次迭代中更改嵌套 for 循环的 个数 迭代变量?
2) 如何实现 word 使其动态地累加所有迭代变量,无论该特定迭代中有多少。
当然,与我建议的完全不同的实现也非常受欢迎。非常感谢!
【问题讨论】:
标签: python-3.x loops nested-loops