I am attempting to create a 2d array, and then subsequently pull data from the array and insert data at a specific point in the array. Below is some code that I wrote for creating the 2D Array:
from array import *
import math, random
TDArrayBuilder = []
TDArray = []
for yrunner in range(3):
for xrunner in range(3):
TDArrayBuilder.append(random.randint(0,1))
TDArray.insert(yrunner, [TDArrayBuilder])
TDArrayBuilder = []
print(TDArray[0][2])
The Error that this is spitting out is as follows:
Traceback (most recent call last):
File "C:/TestFile.py", line 13, in
print(TDArray[0][2])
IndexError: list index out of range
I also wrote some code previous to this regarding finding and printing the minimum values and maximum values in a 2D array, it was easily able to print the value at the specified location. I'm pretty sure this is just because I used numpy, but I would still like to do this without numpy.
Example code:
import numpy as np #required Import
import math
#preset matrix data
location = [] #Used for locations in searching
arr = np.array([[11, 12, 13],[14, 15, 16],[17, 15, 11],[12, 14, 15]]) #Data matrix
result = np.where(arr == (np.amax(arr))) #Find the position(s) of the lowest data or the highest data, change the np.amax to npamin for max or min respectively
listofCoordinates = list(zip(result[0], result[1])) #Removes unnecessary stuff from the list
for cord in listofCoordinates: #takes the coordinate data out, individually
for char in cord: #loop used to separate the characters in the coordinate data
location.append(char) #Stores these characters in a locator array
length = (len(location)) #Takes the length of location and stores it
length = int(math.floor((length / 2))) #Floors out the length / 2, and changes it to an int instead of a float
for printer in range(length): #For loop to iterate over the location list
ycoord = location[(printer*2)] #Finds the row, or y coord, of the variable
xcoord = location[((printer*2)+1)] #Finds the column, or x coord of the variable
print(arr[ycoord][xcoord]) #Prints the data, specific to the location of the variables
Summary:
I would like to be able to retrieve data from a 2d array, and I don't know how to do that (regarding the first code). I made a file using numpy and it worked, however, I would prefer not to use it for this operation as of current. anything would help
from random import randint
TDArray = list()
for yrunner in range(3):
TDArrayBuilder = list()
for xrunner in range(3):
TDArrayBuilder.append(randint(0, 1))
TDArray.insert(yrunner, TDArrayBuilder)
print(TDArray)
print(TDArray[0][2])
or
TDArray = [[randint(0, 1) for _ in range(3)] for _ in range(3)]
print(TDArray)
print(TDArray[0][2])