在每次迭代的嵌套 for 循环中添加一个迭代变量
Add an iteration variable in a nested for-loop on every iteration
我正在尝试编写一个程序来打印两个和四个字符之间所有可能的字母组合。我现在拥有的程序运行良好,但实现远非理想。这是现在的样子:
# 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) 如何在 'mother loop'?
的每次迭代中更改嵌套 for 循环的 number of 迭代变量
2) 如何实现 word 以便动态添加所有迭代变量,无论该特定迭代中有多少。
当然,与我建议的完全不同的实现也非常受欢迎。非常感谢!
无需更改迭代变量的数量,只需将其全部保存在一个元组中,然后使用连接列表理解即可。像这样的东西会起作用:
for iter_tuple in product(ascii, repeat = i):
word = ''.join(chr(x) for x in iter_tuple)
print(word)
我正在尝试编写一个程序来打印两个和四个字符之间所有可能的字母组合。我现在拥有的程序运行良好,但实现远非理想。这是现在的样子:
# 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) 如何在 'mother loop'?
的每次迭代中更改嵌套 for 循环的 number of 迭代变量
2) 如何实现 word 以便动态添加所有迭代变量,无论该特定迭代中有多少。
当然,与我建议的完全不同的实现也非常受欢迎。非常感谢!
无需更改迭代变量的数量,只需将其全部保存在一个元组中,然后使用连接列表理解即可。像这样的东西会起作用:
for iter_tuple in product(ascii, repeat = i):
word = ''.join(chr(x) for x in iter_tuple)
print(word)