正确追加范围 python

Appending correctly with ranges python

这是转置矩阵代码的一部分,该函数接受一个参数,即一系列列表。假设输入是:

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

基本上,输出应该return

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

对于任何矩阵依此类推。 以下代码 returns

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]

然而,当我试图让它跟随列长度时,它 returns 而不是

   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 to map() with an initial argument of None. 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).

要使此 return 列表列表而不是元组列表,return 以下列表理解:

[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 更容易。 :)