如何在python中创建嵌套列表?

时间:2022-05-22 15:49:04

I know you can create easily nested lists in python like this:

我知道你可以在python中创建容易嵌套的列表,如下所示:

[[1,2],[3,4]]

But how to create a 3x3x3 matrix of zeroes?

但是如何创建一个3x3x3的零矩阵?

[[[0] * 3 for i in range(0, 3)] for j in range (0,3)]

or

[[[0]*3]*3]*3

Doesn't seem right. There is no way to create it just passing a list of dimensions to a method? Ex:

似乎不对。没有办法创建它只是将维度列表传递给方法?例如:

CreateArray([3,3,3])

5 个解决方案

#1


9  

In case a matrix is actually what you are looking for, consider the numpy package.

如果矩阵实际上是您正在寻找的,请考虑numpy包。

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html#numpy.zeros

This will give you a 3x3x3 array of zeros:

这将为您提供3x3x3的零数组:

numpy.zeros((3,3,3)) 

You also benefit from the convenience features of a module built for scientific computing.

您还可以享受为科学计算而构建的模块的便利功能。

#2


1  

List comprehensions are just syntactic sugar for adding expressiveness to list initialization; in your case, I would not use them at all, and go for a simple nested loop.

列表推导只是为列表初始化添加表达性的语法糖;在你的情况下,我根本不会使用它们,并去一个简单的嵌套循环。

On a completely different level: do you think the n-dimensional array of NumPy could be a better approach?
Although you can use lists to implement multi-dimensional matrices, I think they are not the best tool for that goal.

在一个完全不同的层面上:你认为NumPy的n维数组可能是一个更好的方法吗?虽然您可以使用列表来实现多维矩阵,但我认为它们不是实现该目标的最佳工具。

#3


1  

NumPy addresses this problem

NumPy解决了这个问题

http://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93

>>> a = array( [2,3,4] )
>>> a
array([2, 3, 4])
>>> type(a)
<type 'numpy.ndarray'>

But if you want to use the Python native lists as a matrix the following helper methods can become handy:

但是,如果要将Python本机列表用作矩阵,则以下辅助方法可以变得方便:

import copy

def Create(dimensions, item):
    for dimension in dimensions:
        item = map(copy.copy, [item] * dimension)
    return item
def Get(matrix, position):
    for index in position:
        matrix = matrix[index]
    return matrix
def Set(matrix, position, value):
    for index in position[:-1]:
        matrix = matrix[index]
    matrix[position[-1]] = value

#4


0  

Or use the nest function defined here, combined with repeat(0) from the itertools module:

或者使用此处定义的嵌套函数,结合itertools模块中的repeat(0):

nest(itertools.repeat(0),[3,3,3])

#5


-3  

Just nest the multiplication syntax:

只需嵌套乘法语法:

[[[0] * 3] * 3] * 3

It's therefore simple to express this operation using folds

因此,使用折叠来表达此操作非常简单

def zeros(dimensions):
    return reduce(lambda x, d: [x] * d, [0] + dimensions)

Or if you want to avoid reference replication, so altering one item won't affect any other you should instead use copies:

或者,如果您想避免引用复制,那么更改一个项目不会影响任何其他项目您应该使用副本:

import copy
def zeros(dimensions):
    item = 0
    for dimension in dimensions:
        item = map(copy.copy, [item] * dimension)
   return item

#1


9  

In case a matrix is actually what you are looking for, consider the numpy package.

如果矩阵实际上是您正在寻找的,请考虑numpy包。

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html#numpy.zeros

This will give you a 3x3x3 array of zeros:

这将为您提供3x3x3的零数组:

numpy.zeros((3,3,3)) 

You also benefit from the convenience features of a module built for scientific computing.

您还可以享受为科学计算而构建的模块的便利功能。

#2


1  

List comprehensions are just syntactic sugar for adding expressiveness to list initialization; in your case, I would not use them at all, and go for a simple nested loop.

列表推导只是为列表初始化添加表达性的语法糖;在你的情况下,我根本不会使用它们,并去一个简单的嵌套循环。

On a completely different level: do you think the n-dimensional array of NumPy could be a better approach?
Although you can use lists to implement multi-dimensional matrices, I think they are not the best tool for that goal.

在一个完全不同的层面上:你认为NumPy的n维数组可能是一个更好的方法吗?虽然您可以使用列表来实现多维矩阵,但我认为它们不是实现该目标的最佳工具。

#3


1  

NumPy addresses this problem

NumPy解决了这个问题

http://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93

>>> a = array( [2,3,4] )
>>> a
array([2, 3, 4])
>>> type(a)
<type 'numpy.ndarray'>

But if you want to use the Python native lists as a matrix the following helper methods can become handy:

但是,如果要将Python本机列表用作矩阵,则以下辅助方法可以变得方便:

import copy

def Create(dimensions, item):
    for dimension in dimensions:
        item = map(copy.copy, [item] * dimension)
    return item
def Get(matrix, position):
    for index in position:
        matrix = matrix[index]
    return matrix
def Set(matrix, position, value):
    for index in position[:-1]:
        matrix = matrix[index]
    matrix[position[-1]] = value

#4


0  

Or use the nest function defined here, combined with repeat(0) from the itertools module:

或者使用此处定义的嵌套函数,结合itertools模块中的repeat(0):

nest(itertools.repeat(0),[3,3,3])

#5


-3  

Just nest the multiplication syntax:

只需嵌套乘法语法:

[[[0] * 3] * 3] * 3

It's therefore simple to express this operation using folds

因此,使用折叠来表达此操作非常简单

def zeros(dimensions):
    return reduce(lambda x, d: [x] * d, [0] + dimensions)

Or if you want to avoid reference replication, so altering one item won't affect any other you should instead use copies:

或者,如果您想避免引用复制,那么更改一个项目不会影响任何其他项目您应该使用副本:

import copy
def zeros(dimensions):
    item = 0
    for dimension in dimensions:
        item = map(copy.copy, [item] * dimension)
   return item