使用 类 和方法在 Python 中创建一个 jagged/ragged 数组

Create a jagged/ragged array in Python using classes and methods

我需要在 Python 中创建一个参差不齐的二维网格,它有 3 行,其中第一行有 3 列,第二行有 6 列,第三行有 9 列。所有这些都应该在不使用任何包(如 NumPy 或其他任何东西)的情况下完成,仅使用 类 和如下例中的方法。这是我如何创建常规二维数组的示例

class newArray ():
    def __init__(self, capacity, fill = None):
        self.item = list()
        for count in range (capacity):
            self.item.append(fill)
            
    def __str__(self):
        return str (self.item)
    
    def __len__(self):
        return len(self.item)
    
    def __iter__(self):
        return iter(self.item)
    
    def __getitem__(self, index):
        return self.item[index]
    
    def __setitem__(self, index, newItem):
        self.item[index] = newItem
        
class raggedGrid():
    
    def __init__(self, rows, cols):
        self.data = newArray(rows)
        for row in range(rows):
            self.data[row] = newArray(cols)
        
                    
    def getRows(self):
        return len(self.data)
    
    def getCols(self):
        return len(self.data[0])
    
    def __getitem__(self, index):
        return self.data[index]
    
    def __setitem__(self, index, newItem):
        self.data[index] = newItem
    
    def __str__(self):
        result = '\n'
        for row in range(self.getRows()):
            for col in range(self.getCols()):
                result += str(self.data[row][col]) + ' '
            result += '\n'
        return result

声明后打印出一个网格

a = raggedGrid(4,4)
print(a)


None None None None 
None None None None 
None None None None 
None None None None 

我卡住了,不知道从哪里开始

这里是 raggedGrid class 的修改版本:

class raggedGrid():
    
    def __init__(self, rows, *col_lengths):
        self.data = newArray(rows)
        for row in range(rows):
            self.data[row] = newArray(col_lengths[row])
        
                    
    def getRows(self):
        return len(self.data)
    
    def getCols(self, row_index=None):
        if row_index is None:
            return [len(self.data[row]) for row in self.data]
        else:
            return len(self.data[row_index])
    
    
    def __getitem__(self, index):
        return self.data[index]
    
    def __setitem__(self, index, newItem):
        self.data[index] = newItem
    
    def __str__(self):
        result = '\n'
        for row_index in range(self.getRows()):
            for col_index in range(self.getCols(row_index)):
                result += repr(self.data[row_index][col_index]) + ' '
            result += '\n'
        return result

这是一个用法示例:

a = raggedGrid(4,2,7,16,3) # Four row, having respective lengths of 2,7,16,3
print(a)
a[1][4] = "Val at [1][4]"
a[2][13] = "Val at [2][13]"
print ("Printing a after some elements were assigned")
print (a)