小编Fin*_*inn的帖子

在向量存在之前用“ end”创建索引数组

我只是想知道end在知道向量的大小之前是否有一种使用索引的方法?它应适用于具有不同大小的阵列。像这样:

subvector = (2:end) % illegal use of end

A=[1 2 3];
B=[4 5 6 7];

A(subvector) % should be 2 3
B(subvector) % should be 5 6 7
Run Code Online (Sandbox Code Playgroud)

arrays indexing matlab matrix-indexing

6
推荐指数
1
解决办法
56
查看次数

在python中将len()和sum()存储为变量的约定

是否有关于何时以及如何在 python 中存储len()或值的约定sum()?举个例子,如果你有一个类

class MyClass:

    def __init__(self, single_number = 4, multiple_numbers = [1,2,3]):
        self.single= single_number 
        self.multiple = multiple_numbers

    def info(self):
        print(f"The length of multiple is {len(self.multiple)}")
        print(f"The length of multiple is {len(self.multiple)*4}")
        print(f"The length of multiple is longer than {len(self.multiple)-1}")

if __name__ == "__main__":
    test=MyClass()
    test.info()
    # other stuff
    test.info()
Run Code Online (Sandbox Code Playgroud)

你会在什么时候开始存储len(self.multiple)它自己的价值?值得庆幸的是,python 在len某些任务中for my_numbers in multiple_numbers:不使用 ,所以我不需要它只用于迭代。此外,len对于类的实例, 的值是静态的,并且在运行时的不同部分(可能)多次需要,所以它不是像这里的临时变量 。一般来说,这似乎是(非常少量的)内存与计算之间的权衡。同样的问题适用于sum().

这些问题的一部分是基于意见的,我很高兴听到您的想法,但我主要是在寻找关于此的约定。

  1. 在什么时候,如果有的话,应该len(self.multiple)作为它自己的值存储?
  2. 名称有约定吗?length_of_multiple_numbers …

python conventions

2
推荐指数
1
解决办法
178
查看次数

标签 统计

arrays ×1

conventions ×1

indexing ×1

matlab ×1

matrix-indexing ×1

python ×1