【问题标题】:Python, For loops depending on intPython,依赖于 int 的 For 循环
【发布时间】:2016-10-21 09:05:58
【问题描述】:

我有一些代码可以打印每个可能的字母组合,字长为 3。

letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"    ,"u","v","w","x","y","z"]
for x in range(0,26):
    for y in range(0,26):
        for z in range(0,26):
            print(letters[x],letters[y],letters[z])

这段代码运行良好,但如果我想查看每个 4 个字母的单词,那么我将不得不添加另一个 for 循环,并且对于 5 个字母等等。

我想知道如何根据用户输入进行一定数量的 for 循环。

【问题讨论】:

标签: python


【解决方案1】:

itertools.product*repeat=n* 其中 n 是多少循环:

from itertools import  product
for p in product(letters,repeat=3):
    print(p)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-18
    • 2017-12-05
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多