如何在 Python 中处理嵌套列表?我在弄清楚语法时遇到问题。像例子:
>>> l = [[1, 2, 3], [5, 6, 7]]
我想对这个列表中的所有元素求平方。我试过:
[m*m for m in l]
但这不起作用并抛出:
TypeError: can't multiply sequence by non-int of type 'list'
我猜是因为嵌套列表?
我该如何解决这个问题?
最佳答案
>>> l = [[1, 2, 3], [5, 6, 7]]
>>> [[e*e for e in m] for m in l]
|-nested list-|
|---- complete list ---|
[[1, 4, 9], [25, 36, 49]]
关于python - 修改嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4370641/