python - Python:一行中的双重for循环
问题描述
我有这样一个循环:
for i in range(len(A)):
for j in range(len(A[i])):
A[i][j] = functionA(A[i][j])
这有可能在 Python 中写得更紧凑吗?
解决方案
您可以使用列表理解。
示例代码:
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]]
推荐阅读
- javascript - JavaScript 文件中的 VS Code 格式 HTML (ReactJS)
- bash - 删除超过 15 天的 *.ZIP 文件
- python - python pandas中日期时间行的GroupBy日期
- excel - 运行时错误:查看#N/A 字符串时显示 13
- python - 如果行具有相同的“A 列”值,则用最后一个已知值填充空的“B 列”单元格
- python - 如何有效地将随机数添加到数组中,直到达到累积和?
- python - 在 pandas 中将单项系列作为元组返回
- python - IF 在 Python 中使用 Selenium 验证 XPATH 的问题
- wordpress - 带有革命滑块的锚链接
- web-crawler - 使用 Apify SDK 时有没有办法指定最大爬网深度?