重复数组并停在特定位置w/numpy [英] Repeat array and stops at specific position w/ numpy
问题描述
我必须编写一个循环函数cyclisch(N)
,该循环函数构造长度为N的内容为[1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...]
的Numpy行.
I have to write a cyclic functie cyclisch(N)
that constructs a Numpy-row with length N with content[1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...]
.
这是我现在拥有的密码.
This is de code I'm having now.
import numpy as np
import math
def cyclisch(N):
r = np.linspace(float(1.0), float(3.0), 3)
return np.repeat(r, N//3) + r[0:N%3-1]
我多次尝试使列表"r"浮动,但出现错误:
I tried multiple times to make the list 'r' float, but I get the error:
only length-1 arrays can be converted to Python scalars
此外,重复代码也是错误的.通过重复编码,您将得到:
Further, the repeating code is also wrong. With the repeat coding you get:
[ 1. 1. 2. 2. 3. 3.]
而不是[1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...]
.有人知道如何拥有这种重复代码吗?
Instead of [1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...]
. Does anyone know how to have this kind of repeating code?
这是控制模式:
p = cyclisch(10)
q = cyclisch(7)
assert np.all(p == np.array([ 1., 2., 3., 1., 2., 3., 1., 2., 3., 1.])),'Fout resultaat van cyclisch(10)'
assert np.all(q == np.array([ 1., 2., 3., 1., 2., 3., 1.])),'Fout resultaat van cyclisch(7)'
print('Correct !')
谢谢您的帮助!
推荐答案
您可以使用 np.resize .
>>> np.resize([1., 2., 3.], 5)
array([ 1., 2., 3., 1., 2.])
此功能自以下日期起生效:
This works since:
如果新数组大于原始数组,则新数组将填充a的重复副本.
If the new array is larger than the original array, then the new array is filled with repeated copies of a.
请注意,np.ndarray.resize
方法具有不同的行为,用零填充(并且对数组进行突变而不是使用新的填充),因此您需要使用函数而不是方法.
Note that the np.ndarray.resize
method has different behavior, padding with zeros (and also mutating the array instead of making a new one), so you need to use the function, not the method.
这篇关于重复数组并停在特定位置w/numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!