【问题标题】:Add an iteration variable in a nested for-loop on every iteration在每次迭代的嵌套 for 循环中添加迭代变量
【发布时间】: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


    【解决方案1】:

    无需更改迭代变量的数量,只需将其全部保存在一个元组中,然后使用连接列表推导。这样的事情会起作用:

    for iter_tuple in product(ascii, repeat = i):
        word = ''.join(chr(x) for x in iter_tuple)
        print(word)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 2020-05-04
      • 2015-03-19
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多