简体   繁体   中英

2d list / matrix in python

I am trying to create a 4x4 matrix class in python...

I had the matrix being created like this -

class matrix:
    self.matrix = [[0 for x in range(4)] for y in range(4)]

i have tried to access the indices in this matrix like this for example -

myMatrix = matrix()
print(myMatrix.matrix[0][0])

however I get an error saying

AttributeError: myMatrix instance has no attribute '__getItem__'

I have tried adding a method to my matrix class like this-

def getValue(self, x, y):
    return self.matrix[x][y]

but I get an error saying TypeError: list indices must be integers

even when I tried self.matrix[0][0] it said they must be integers, any idea on how I can get simple 2d list/ matrix functionality in python?

I just want to be able to create a 4x4 2d list / matrix and access and change elements within it?

Yuo should initialize the matrix first, using an __init__ method:

class matrix:
    def __init__(self):
        self.matrix = [[0 for x in range(4)] for y in range(4)]

myMatrix = matrix()
print(myMatrix.matrix[0][0]) # => 0

And now you can create your getValue , which is better for later use:

class matrix:
    def __init__(self):
        self.matrix = [[0 for x in range(4)] for y in range(4)]
    def getValue(self, x, y):
        return self.matrix[x][y]

myMatrix = matrix()
print(myMatrix.matrix[0][0]) # => 0
print(myMatrix.getValue(0, 0)) # => 0

Initialize the matrix in __init__ method and define how to get element by index in __getitem__ .

class matrix:
    def __init__(self):
        self.matrix = [[0 for x in range(4)] for y in range(4)]

    def __getitem__(self, item):
        return self.matrix[item]

m = matrix()
print(m[0][0]) # 0

But, as mentioned before, you can use numpy and other appropriate packages unless you need to implement some special extra-functionality for the matrix.

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