Python列表推导-转置 [英] Python List Comprehensions - Transposing
本文介绍了Python列表推导-转置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是通过阅读此处的矩阵转置教程.我理解了这个示例,但是我试图找到一种无需对范围进行硬编码即可转置矩阵的方法.
I'm just starting out with list comprehensions by the reading the matrix transposing tutorial here. I understand the example, but I'm trying to figure out a way to transpose the matrix without hardcoding the range in.
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
lcomp = [[row[i] for row in matrix] for i in range(4)]
print(lcomp)
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #result
而不是range(4)
,我希望它能够找出最大的嵌套数组具有的最大元素数.我尝试放置lambda
,但不断从中获取错误.可以单线执行此操作吗?
Instead of range(4)
, I want it to be able to figure out the the max number of elements that the largest nested array has. I tried placing a lambda
but kept getting errors from it. Is it possible to do this in a one-liner?
推荐答案
您可以使用另一种理解方式!他们是一个非常强大的工具.
You can use another comprehension! They're a very powerful tool.
[[row(i) for row in matrix] for i in range(max(len(r) for r in matrix))]
这篇关于Python列表推导-转置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文