python 数组表示法 shorthand :"k%parents.shape[0]" 是什么意思?
python array notation shorthand :"k%parents.shape[0]" mean?
我今天遇到了这个表示法
本教程在这里:https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6
parent1_idx = k%parents.shape[0]
return 右边是什么?
这种表达的名称是什么?
提前致谢!
%
是 python 中的运算符,即 Modulus operator - it gives remainder of the division of left operand by the right
我在上述文章的这段代码中看到了这一行:
for k in range(offspring_size[0]):
# Index of the first parent to mate.
parent1_idx = k%parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1)%parents.shape[0]
其中parents
定义如下:
parents = numpy.empty((num_parents, pop.shape[1]))
for parent_num in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
max_fitness_idx = max_fitness_idx[0][0]
parents[parent_num, :] = pop[max_fitness_idx, :]
fitness[max_fitness_idx] = -99999999999
return parents
从以上两行可以看出,k
和 parents.shape[0]
都是整数,因此该行是两个数值变量之间的简单 modulo operator:a = b % c
。
我今天遇到了这个表示法 本教程在这里:https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6
parent1_idx = k%parents.shape[0]
return 右边是什么? 这种表达的名称是什么? 提前致谢!
%
是 python 中的运算符,即 Modulus operator - it gives remainder of the division of left operand by the right
我在上述文章的这段代码中看到了这一行:
for k in range(offspring_size[0]):
# Index of the first parent to mate.
parent1_idx = k%parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1)%parents.shape[0]
其中parents
定义如下:
parents = numpy.empty((num_parents, pop.shape[1]))
for parent_num in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
max_fitness_idx = max_fitness_idx[0][0]
parents[parent_num, :] = pop[max_fitness_idx, :]
fitness[max_fitness_idx] = -99999999999
return parents
从以上两行可以看出,k
和 parents.shape[0]
都是整数,因此该行是两个数值变量之间的简单 modulo operator:a = b % c
。