简体   繁体   中英

Create a multidimensional array in python without additional library?

def create_nd_array(dimensions, value):
"""Function will create a N-dimensional array.
    A N-dimensional array will be filled by the value being passed to the function.
Parameter:
Input:
    value(int or bool or string): Newly formed N-dimensional array will contain this particular value.
    dimensions(tuple): tuple indicating dimensions of newly formed N-dimensional array.
Output:
    array_nd(N-dimensional array): a N-dimensional array  of values."""
dimension_length = len(dimensions)
array_nd = value
for index in range(dimension_length - 1, -1, -1):
    dimension = dimensions[index]
    array_nd = [array_nd for _ in range(dimension)].copy()
return array_nd

I have written above code. This will create a N-Dimensional array with aliasing.When I am mutating the list it will mutate everything. eg aliasing problem <--click here

You need not copy the list, instead you can append it to a result list; and also instead of range(dimension_length - 1, -1, -1) , you can directly take the dimensions without using their indices by puttng dimensions[::-1] like this

def create_nd_array(dimensions, value):
    array_nd = []

    for dim in dimensions[::-1]:
        array_nd.append([value for _ in range(dim)])

    return array_nd

print(create_nd_array((2,4,2), 0))

This can be further compressed into a List comprehension as

def create_nd_array(dimensions, value):
    array_nd = [[value for _ in range(dim)] for dim in dimensions[::-1]]
    return array_nd

print(create_nd_array((2,4,2), 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM