我如何使一个for循环金字塔更简洁的Python? [重复]

这个问题已经有一个答案在这里:            >            Python nested looping Idiom                                    4个答案                            在实体力学中,我经常使用Python并编写如下代码:

for i in range(3):
    for j in range(3):
        for k in range(3):
            for l in range(3):
                # do stuff

我经常这样做,我开始怀疑是否有一个更简洁的方法来做到这一点。当前代码的缺点是:如果我符合PEP8,那么我不能超过每行79个字符的限制,并且没有太多的空间,特别是如果这又是一个类的函数。

根据你想做什么,你可以使用itertools模块来最小化for循环(或zip)。在这种情况下,itertools.product将创建你用4个循环做的:

>>> list(product(range(3),repeat=4))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 1, 0), (0, 0, 1, 1),
 (0, 0, 1, 2), (0, 0, 2, 0), (0, 0, 2, 1), (0, 0, 2, 2), (0, 1, 0, 0),
 (0, 1, 0, 1), (0, 1, 0, 2), (0, 1, 1, 0), (0, 1, 1, 1), (0, 1, 1, 2),
 (0, 1, 2, 0), (0, 1, 2, 1), (0, 1, 2, 2), (0, 2, 0, 0), (0, 2, 0, 1),
 (0, 2, 0, 2), (0, 2, 1, 0), (0, 2, 1, 1), (0, 2, 1, 2), (0, 2, 2, 0),
 (0, 2, 2, 1), (0, 2, 2, 2), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 0, 2),
 (1, 0, 1, 0), (1, 0, 1, 1), (1, 0, 1, 2), (1, 0, 2, 0), (1, 0, 2, 1),
 (1, 0, 2, 2), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 0, 2), (1, 1, 1, 0),
 (1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 2, 0), (1, 1, 2, 1), (1, 1, 2, 2),
 (1, 2, 0, 0), (1, 2, 0, 1), (1, 2, 0, 2), (1, 2, 1, 0), (1, 2, 1, 1),
 (1, 2, 1, 2), (1, 2, 2, 0), (1, 2, 2, 1), (1, 2, 2, 2), (2, 0, 0, 0),
 (2, 0, 0, 1), (2, 0, 0, 2), (2, 0, 1, 0), (2, 0, 1, 1), (2, 0, 1, 2),
 (2, 0, 2, 0), (2, 0, 2, 1), (2, 0, 2, 2), (2, 1, 0, 0), (2, 1, 0, 1),
 (2, 1, 0, 2), (2, 1, 1, 0), (2, 1, 1, 1), (2, 1, 1, 2), (2, 1, 2, 0),
 (2, 1, 2, 1), (2, 1, 2, 2), (2, 2, 0, 0), (2, 2, 0, 1), (2, 2, 0, 2),
 (2, 2, 1, 0), (2, 2, 1, 1), (2, 2, 1, 2), (2, 2, 2, 0), (2, 2, 2, 1),
 (2, 2, 2, 2)]

在你的代码中,你可以做:

for i,j,k,l in product(range(3),repeat=4):
    #do stuff

This function is equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:

06002

编辑:As @ PeterE说在注释product()可以使用,即使范围有不同的长度:

product(range(3),range(4),['a','b','c'] ,some_other_iterable)
http://stackoverflow.com/questions/28382433/how-can-i-make-a-for-loop-pyramid-more-concise-in-python

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:我如何使一个for循环金字塔更简洁的Python? [重复]