是否可以将两次迭代转换为' itertools.chain'用Python操作?

时间:2017-09-03 03:45:53

标签: python itertools

我正在阅读Python书并遇到了#iteffools.chain'。我想知道是否可以将以下关于2D阵列的代码转换为' itertools.chain'。

我的第二个问题是:使用' itertools.chain'有什么好处?与两个for-loops相比?

for row in range(rows):
    some operation on rows
    for col in range(columns):
        some operations on cell i,j

谢谢!

1 个答案:

答案 0 :(得分:2)

你不会在这里使用chain,因为chain每行会运行一次,然后每列运行一次(#rows + #cols),而不是每个单元(#rows *# COLS)。

你想要的是itertools.product。但它只有在你单独操作细胞时才有效;如果你需要执行每行操作,你最好使用显式嵌套循环。 product方法是:

for row, col in itertools.product(range(rows), range(columns)):
    some operations on cell row,col