这是用于转置矩阵的代码的一部分,该函数采用一个参数,即列表的列表。假设输入是:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
基本上,输出应该返回
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
对于任何矩阵依此类推。 以下代码返回
def matrix(data)
column = len(data)
transposed[0].append(data[0][0])
transposed[0].append(data[1][0])
transposed[0].append(data[2][0])
outputs [1,4,7]
但是,当我尝试让它跟随列长度时,它会返回
transposed[0].append(data[0:column][0])
outputs [1,2,3]
我的代码有什么问题?
请您参考如下方法:
您可以使用内置函数 zip 转置矩阵:
def transpose(m):
return zip(*m)
来自文档:
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length,
zip()is similar tomap()with an initial argument ofNone. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using
zip(*[iter(s)]*n).
要使其返回列表列表而不是元组列表,请返回以下列表理解:
[list(r) for r in zip(*m)]
以下是使用追加的方法:
def transpose(m):
transposed = [[] for _ in range(len(m[0]))]
for i in range(len(m)):
for j in range(len(m[0])):
transposed[j].append(m[i][j])
return transposed
如您所见,使用 zip 更容易。 :)
