Python:使用列表编写转置函数时出错

问题描述 投票:1回答:2

我有一个要做的任务,那就是:

编写一个函数转置,它接收一个矩阵并对其进行转置。基本上,这将m×n矩阵转换为n×m矩阵。

我写了一个看似合理的代码,但它并没有让我得到我想要的结果。任何人都可以指出我的代码有什么问题吗?

def transpose(matrix):
    new_matrix=[[]]*len(matrix[0])
    for row in matrix:
        i=0
        for j in row:
            new_matrix[i]+=[j]
            i+=1
    return new_matrix

测试用例:

print(transpose([[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
python-3.x list
2个回答
1
投票

如果使用*在列表初始化中乘以某些值,请小心。您最终可能会将多次引用指向相同的值:

l = [ [] ]*3
print(l)

l[1].append(34)  # change only "the first" list by appending smth
print(l)

输出:

[[], [], []]
[[34], [34], [34]]  # they are all "the same data" reference

有一个内置的zip(),完全符合你的转置:

l = [[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 


l_t = [ list(x) for x in zip(*l)]  # one-line solutions for transposing ;)

print(l)
print(l_t) # transposed

Zip有一个限制,它只适用于最小的子列表的长度 - 你的都是相同的,所以一切都很好。

输出:

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

如果您需要一个包含最长列表的zip,可以使用itertools.zip_longest(..),它需要一个默认的参数来代替任何不存在的较短列表项。

顺便说一句。只是list(zip(l))看起来像这样:[(1,5,9),(2,6,10),(3,7,11),(4,8,12)] - 它在你输入的可迭代部分的相同索引上创建元组。


用手:

l = [[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 


l2 = []
for colIdx in range(len(l[0])):  # 0-3 iterate over the inner indexes first
    newRow = []
    for rowIdx in range(len(l)): # 0-2 then over the outer ones 
        newRow.append(l[rowIdx][colIdx])
    l2.append(newRow)

print(l2)  # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

1
投票

我的意思是这样的:

def t(array): #The original array has size mxn
    duplicate = [[0 for x in range(len(array))] for y in range(len(array[1]))] #You create an array of size nxm, which is filled with zeros
    for i in range(len(array)): #Loop over the rows
        for j in range(len(array[i])): #Then loop over the columns
            duplicate[j][i] = array[i][j] #Replace j,i or duplicate with i,j th element of original
    return duplicate

现在,

>>> t([[ 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
© www.soinside.com 2019 - 2024. All rights reserved.