我必须编写一个循环函数 cyclisch(N)
,它构造一个长度为 N 的 Numpy 行,内容为 [1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...]
.
这是我现在拥有的代码。
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” float ,但出现错误:
only length-1 arrays can be converted to Python scalars
此外,重复代码也是错误的。通过重复编码,您将获得:
[ 1. 1. 2. 2. 3. 3.]
而不是 [1.0 2.0 3.0 1.0 2.0 3.0 1.0 2.0 3.0 ...]
。有谁知道怎么会有这种重复的代码吗?
这是控制模式:
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.])
这是因为:
If the new array is larger than the original array, then the new array is filled with repeated copies of a.
请注意,np.ndarray.resize
方法 具有不同的行为,用零填充(并且还改变数组而不是创建新数组),因此您需要使用功能,而不是方法。
关于python - 重复数组并在特定位置停止 w/numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45129775/