简体   繁体   中英

How to create multi-dimensional array typedef in Python

In C++, one can create a typedef for 1D, 2D arrays and then use them to declare variables.

typedef char my2DDataArr[2][2];
typedef int my1DDataArr[10];

my2DDataArr arr2d_1= {{0,1},{2,3}};
my1DDataArr arr1d_1 = {1,2,3,4,5,6,7,8,9,10};

How can I accomplish similar in Python ?

The Python equivalent would be

arr2d_1 = [[0,1],[2,3]]
arr1d_1 = [1,2,3,4,5,6,7,8,9,10]

There's no typedef and no need to specify a variable's type. At most you could do:

arr2d_1:list = [[0,1],[2,3]]
arr1d_1:list = [1,2,3,4,5,6,7,8,9,10]

But even then, the :list part is called a type hint , which will help some IDEs in refactoring, it's not a strict requirement for the interpreter.

Python is strongly but dynamically typed. That means that you don't need to let the compiler know what type a variable will be - mostly because python code isn't compiled.

So obviously you could simply do something like:

my_list = [] # List that can contain other lists, could be 1D or nD        
initialized_list = [[1, 2], [2, 4]]

Now as I wrote the list can contain other lists. Some people don't like the uncertainty and lack of readability when you don't define the type of the variable. For that you do have two different solutions:

import numpy as np
my_array = np.ndarray((2, 2)) # 2D Array
initialized_array = np.array([[1, 2], [2, 4]])

Now that notation should look more familiar to you, as that is a 2 dimensional array. Unlike a list it can and will have only 2 dimensions, 4 elements total (2x2). If you don't care about the array being immutable and/or want mutability you can just use type-hints :

from typing import List
my_list: List[List[int]]
my_list = []

Writing it like this says that it's a list that will contain lists of integers. Size is still not limited but a smart IDE will give you warnings if you start putting something else into it or if you make it 3 dimensional.

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