如何在python中使用循环转置二维列表数组? [英] How to transpose a 2D list array using loops in python?

查看:79
本文介绍了如何在python中使用循环转置二维列表数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有:

a = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]]

我想将其转置为:

a = [[1,0,4], [1,2,0], [1,-1,10], [6,3,42]]

在python中使用循环.我目前的代码是:

using loops in python. The current code that I have is:

def transpose(a):
    s = []
    for row in range(len(a)):
        for col in range(len(a)):
            s = s + [a[col][row]]
return s

但这给了我以下输出:

[1, 0, 4, 1, 2, 0, 1, -1, 10]

取而代之的是:

[[1,0,4], [1,2,0], [1,-1,10], [6,3,42]]

谁能帮帮我?我对这个东西还是个新手,不明白为什么它不起作用.非常感谢!

Can anyone help me? I'm still new at this stuff and don't understand why it doesn't work. Thanks so much!

推荐答案

以下是基于您的代码的解决方案:

Here is a solution that is based on your code:

def transpose(a):
    s = []
    # We need to assume that each inner list has the same size for this to work
    size = len(a[0])
    for col in range(size):
        inner = []
        for row in range(len(a)):
            inner.append(a[row][col])
        s.append(inner)
    return s

如果你为内部循环定义了一个内部列表,你的输出是这样的:

If you define an inner list for the inner loop, your output is this:

[[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]]

这篇关于如何在python中使用循环转置二维列表数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆