首页 > 解决方案 > Python:一行中的双重for循环

问题描述

我有这样一个循环:

    for i in range(len(A)):
        for j in range(len(A[i])):
            A[i][j] = functionA(A[i][j])

这有可能在 Python 中写得更紧凑吗?

标签: pythonfor-loop

解决方案


您可以使用列表理解。

示例代码:

A = [[1,2,3],[4,5,6],[7,8,9]]
def functionA(a):
    return a+1

A = [[functionA(A[i][j]) for j in range(len(A[i]))] for i in range(len(A))]
print(A)

结果:

[[2, 3, 4], [5, 6, 7], [8, 9, 10]]

推荐阅读