将列表转换为矩阵(python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28752146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:41:08  来源:igfitidea点击:

Convert list to matrix (python)

pythonlistmatrix

提问by SecondLemon

I would like to convert a list to a matrix so that I can use the .append function the way I need it. list = ["1", "2", "3"]should become [["1", "2", "3"]].

我想将列表转换为矩阵,以便我可以按照我需要的方式使用 .append 函数。 list = ["1", "2", "3"]应该成为[["1", "2", "3"]].

Then when I use list.append(["4", "5", "6"])it will become [["1", "2", "3"], ["4", "5", "6"]]instead of ["1", "2", "3", ["4", "5", "6"]].

然后当我使用list.append(["4", "5", "6"])它时会变成[["1", "2", "3"], ["4", "5", "6"]]而不是["1", "2", "3", ["4", "5", "6"]].

How can I do this?

我怎样才能做到这一点?

回答by inspectorG4dget

Do you mean this (a matrix as a list of lists):

你的意思是这个(矩阵作为列表列表):

In [1]: matrix = [[1,2,3]]

In [2]: matrix
Out[2]: [[1, 2, 3]]

In [3]: matrix.append([4,5,6])

In [4]: matrix
Out[4]: [[1, 2, 3], [4, 5, 6]]

回答by aruisdante

This can be done very easily:

这可以很容易地完成:

def list_to_matrix(lst):
    return [lst]

Usage:

用法:

>>> lst = [1,2,3,4]
>>> lst = list_to_matrix(lst)
>>> lst
[[1,2,3,4]]

If we have cases where we might get things that are already in list-of-list form, we can add a little more robustness by doing this:

如果我们有可能得到列表形式的东西,我们可以通过这样做来增加一点健壮性:

from collections import Iterable

def list_to_matrix(lst):
    if lst:
        return lst if all(isinstance(item, Iterable) and not isinstance(item, str) for item in lst) else [lst]
    else:
        # returns empty matrix if input list was empty
        return [[]]

Note that this method is pretty fragile, but at least allows you to safely pass either a base list or a list of list form blindly and get back the correct thing.

请注意,此方法非常脆弱,但至少可以让您安全地盲目传递基本列表或列表形式的列表并返回正确的内容。

回答by mafonya

This works for any objects in list. It gives to every object its coordinates in pseudo 2d list:

这适用于列表中的任何对象。它在伪二维列表中为每个对象提供其坐标:

def to_matrix(l, n):
    return [(x[0] / n, x[0] % n , x) for x in l]

The output for to_matrix([objects], 3)would be:

输出为to_matrix([objects], 3)

[(0, 0, some_object),
 (0, 1, some_object),
 (0, 2, some_object),
 (1, 0, some_object),
 (1, 1, some_object),
 (1, 2, some_object),
 (2, 0, some_object),
 (2, 1, some_object),
 (2, 2, some_object)]

If you need a real 2d array, this code will do the job:

如果您需要一个真正的二维数组,此代码将完成这项工作:

def toMatrix(l, n):
    matrix = []
    for i in range (0, len(l), n):
        matrix.append(l[i:i+n])

    return matrix