How to create nested lists in python?

前端 未结 5 384
无人及你
无人及你 2021-01-13 01:14

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

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

But how to create a 3x3x3 matrix of zeroes?

[[         


        
相关标签:
5条回答
  • 2021-01-13 01:44

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

    nest(itertools.repeat(0),[3,3,3])
    
    0 讨论(0)
  • 2021-01-13 01:54

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

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

    This will give you a 3x3x3 array of zeros:

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

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

    0 讨论(0)
  • 2021-01-13 01:54

    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
    
    0 讨论(0)
  • 2021-01-13 02:08

    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.

    0 讨论(0)
  • 2021-01-13 02:09

    NumPy addresses this problem

    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:

    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
    
    0 讨论(0)
提交回复
热议问题