繁体   English   中英

在特定位置返回值

[英]Returning Values at Specific Positions

Returns a new matrix with the given shape, filled with the given value.
#   value is a single float or integer value used to fill the new matrix.
#   shape is a tuple (number of rows, number of columns) for the new matrix.
# This is a static method that builds the contents and calls the Matrix constructor.
def of(value, shape: tuple):
    contents = []
    for i in range(shape[0]):
        row = []
        for j in range(shape[1]):
            row.append(value)
        contents.append(row)
    return Matrix(contents)

问题已回答! 我将代码配置为完全符合我的期望。 使用 append 对我来说是不熟悉的,在我收到答案后,我能够相应地实现它。 谢谢!

没有必要循环。 只需使用key的两个元素作为索引。

def __getitem__(self, key: tuple):
    i = key[0] % self.shape[0]
    j = key[1] % self.shape[1]
    return self.contents[i][j]

您的代码甚至没有迭代,因为它在循环内无条件返回。 它永远不会进入第二个循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM