How to create nested lists in python?

前端 未结 5 389
无人及你
无人及你 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 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)
    
    

    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
    

提交回复
热议问题