0

I want to be able to get a coordinate system for a 1D array without the use of a library or converting it into a 2D array in Python. Just wondering whether or not if it was possible.

For example:

[0, 1, 2, 3, 4, 5 ,6, 7, 8, 9, 10, 11]

into something like this:

[0, 1, 2, 3,
 4, 5, 6, 7,
 8, 9, 10, 11]

where the index of 7 would be (3, 1).

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
KingBo
  • 1
  • `[data[x:x+4] for x in range(0, len(data), 4)]` will convert to 2d list. – 001 Feb 02 '21 at 13:03
  • Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – Tomerikoo Feb 02 '21 at 13:15

1 Answers1

2

You would have to use functions to transpose your coordinates into flat indexes and store the dimensions somewhere.

A = [0, 1, 2, 3, 4, 5 ,6, 7, 8, 9, 10, 11]

ROWS = 3
COLS = 4

def getItem(a,c,r): return a[r*COLS+c]

def setItem(a,c,r,value): a[r*COLS+c] = value 

print(getItem(A,3,1)) # 7

You could do this in a wrapper class that reads and writes the original list. Here is an example:

class as2D:
    def __init__(self,data,cols):
        self.data = data
        self.cols = cols
        
    @property
    def rows(self): return len(self.data)//self.cols
    
    def __getitem__(self,index):
        return self.data[index[1]*self.cols+index[0]]

    def __setitem__(self,index,value):
        self.data[index[1]*self.cols+index[0]] = value

    def __repr__(self):
        return "["+",\n ".join(", ".join(map(str,self.data[r:r+self.cols])) for r in range(0,len(self.data),self.cols))+"]"

usage:

A = [0, 1, 2, 3, 4, 5 ,6, 7, 8, 9, 10, 11]

A2d = as2D(A,4)

A2d[3,1] # 7

A2d[2,2] = 99

print(A2d)

[0, 1, 2, 3,
 4, 5, 6, 7,
 8, 9, 99, 11]

print(A)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99, 11]

Note that there would be several more "magic" methods to implement for it to be complete, including processing of slices in get/set item functions.

Alain T.
  • 40,517
  • 4
  • 31
  • 51