Glavni problem sa predstavljanjem višedimenzionalnih nizova u strukturama podataka je taj što struktura podataka neće moći efikasno pristupiti elementima u nizu.
A multidimensional array is an array of arrays, or an array whose elements are themselves arrays. The simplest way to represent a multidimensional array in a data structure is to use a list of lists. For example, the following code creates a two-dimensional array with three rows and four columns: array = [[0 for i in range(4)] for j in range(3)] This approach has the advantage of being very simple and easy to understand. However, it is not very efficient, since each element in the array is actually a reference to another list. A more efficient way to represent a multidimensional array is to use a single list, but store the indices of the elements in each row separately. For example, the following code creates a two-dimensional array with three rows and four columns: array = [0] * 12 # create a list with 12 elements indices = [0, 4, 8] # create a list of indices for each row for i in range(3): # loop through each row for j in range(4): # loop through each column in the row array[indices[i] + j] = i * 4 + j # set the element at the index to be the value print(array)
Ovaj pristup je efikasniji jer koristi samo jednu listu, a indeksi elemenata u svakom redu se pohranjuju zasebno.
Višedimenzionalni nizovi
Višedimenzionalni niz je niz koji može pohraniti više vrijednosti u istom prostoru. U Pythonu se višedimenzionalni niz kreira pomoću liste ključnih riječi. Sljedeći primjer koda kreira dvodimenzionalni niz pod nazivom myArray:
myArray = [1, 2]
Prva dimenzija myArray-a je 1, a druga dimenzija je 2.
Struktura podataka
U Pythonu, struktura podataka se odnosi na način na koji su podaci organizirani. Postoji nekoliko različitih tipova struktura podataka koje se mogu koristiti u Pythonu, uključujući liste, rječnike, skupove i stabla.