python - 如何使用 numpy 数组中的索引进行计算

标签 python arrays numpy

所以我希望 perimeterpoints 函数能够工作,但我不确定如何运行数组的索引。我认为我的数组的 len 可以工作,但它说“in”对象不可迭代。因此,如果我有 10 个点,则会产生 0 到 9 的索引。

import math as m
import numpy as np
def ball(numpoints):
    rr = 5. #radius of the ball
    xx = np.linspace(-5,5,numpoints) #x coordinates
    yy = np.array([m.sqrt(rr**2 - xxi**2) for xxi in xx]) #y coordinates
    perimeterpoints = np.array([m.sqrt((xx[i+1]-xx[i])**2+(yy[i+1]-yy[i])**2) for i in range(len(xx)-1)])
    perimeter = sum(perimeterpoints)
    return(perimeter)

提前致谢

编辑

我想我明白了。我将 range() 放在 len(xx)-1 周围,我在上面的代码中修复了它。我得到了正确的答案

最佳答案

使用numpy,您不需要显式迭代。您可以使用索引范围,例如xx[1:] 对应于使用 i+1 进行索引。 xx[:-1],最后一个。

def ball(numpts):
    rr = 5
    xx = np.linspace(-5,5,numpts)
    yy = np.sqrt(rr**2-xx**2)
    perimeterpoints = np.sqrt((xx[1:]-xx[:-1])**2+(yy[1:]-yy[:-1])**2)
    perimeter = np.sum(perimeterpoints)
    return perimeter

关于python - 如何使用 numpy 数组中的索引进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22263059/

相关文章:

不能从 class.__dict__ 调用 python 类方法

php - 如何访问此 XML 中的元素

c - 将字符串分配给变量

python - 初始化高维稀疏矩阵

python - Pandas 数据框 groupby : produce multiple output columns

python - 获取装饰器的可变关键字参数的值

Python Tkinter 可以安全地 self.quit 或 sys.exit 吗?

Python - Tkinter RadioButton If 语句

javascript - 在 Javascript/underscore 上按对象键降序排序

Python dataframe 添加一列选择上一个日期的数据