python - 重复数组并在特定位置停止 w/numpy

标签 python python-3.x numpy

我必须编写一个循环函数 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/

相关文章:

python - 如何使用 Selenium 来点击某些东西

python - 使用 Selenium 单击 'Load More' 按钮直到它不存在(Youtube)

python - IterativeImputer - 样本后验

python - 如何在调用 API 时避免或跳过 python 中的错误 400

python - 用 numpy 数组中的元组替换整数?

python - Windows 命令提示符在 Python 中不起作用

python - 冒泡错误条件的pythonic方法是什么

Python "in"魔术方法?

python - 计算日志变化的替代方法会产生不同的结构

python - 以 COO 格式构建图连接矩阵