使用itertools.product()减少嵌套

时间:2015-07-09 15:14:09

标签: python nested-loops itertools

我知道itertools.product()是解决嵌套循环的有效而快速的解决方案。但是,如果在非最内层的循环中有其他语句,它的使用会变得更加棘手,如下所示:

for i in ...:
    #- Do some stuff here
    for j in ...:
        if j % 2 == 0:
            #- Do more stuff if j is even
        for k in ...:
            #- Do stuff in innermost loop

使用itertools.product()或多或少直接进行重构并确实减少了嵌套,但它存在严重的性能问题。

import itertools, timeit

s1 = """\
n = 10
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
for i in lst:
    a = 2 + 2
    for j in range(n):
        if j % 2 == 0:
            a = 2 * 2
        for k in range(n):
            a = a"""

print('Nested loops runtime:', timeit.timeit(stmt = s1, number = 100000))

s2 = """\
n = 10
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
idx_i_prev = idx_j_prev = -1
for (idx_i, i), (idx_j, j), k in itertools.product(
enumerate(lst), enumerate(range(n)), range(n)):
    if idx_i != idx_i_prev:
        a = 2 + 2
    if idx_j != idx_j_prev:
        if j % 2 == 0:
            a = 2 * 2
    a = a
    idx_i_prev = idx_i
    idx_j_prev = idx_j"""

print('\'itertools\' runtime:', timeit.timeit(stmt = s2, number = 100000))

输出:

Nested loops runtime: 7.883076536934823
'itertools' runtime: 17.23935990303289

因此,我的问题是:有没有一种方法可以在不损害性能的情况下重构嵌套循环?

0 个答案:

没有答案