Python - 使用计算值填充数组

问题描述 投票:0回答:2

我有一个函数定义为:我的代码中的def f2(x),我想得到该函数的x和y值列表。这是我的代码:

     x = np.linspace(-2, 2, 100)
     print("\nx values:\n ", x)

     f2y = np.zeros(len(x))
     # print("f2y, empty array of y values: ", f2y)

     for i in range(0, len(x), 1):
        for j in x:
            f2y[i] = f2(j)

假设f2y数组根据插入的x值填充不同的y值。但是,f2y数组在其数组中获得相同的值。

python
2个回答
0
投票

如果我理解正确,你需要这样的东西:

 import numpy as np
 x = np.linspace(-2, 2, 100)
 #print("\nx values:\n ", x)
 #print len(x)

 f2y = np.zeros(len(x))
 #print("f2y, empty array of y values: ", f2y)
 #print len(f2y)
 f2y = [i for i in x]
 print f2y

0
投票

来吧,试一试。

# declare a list of x values
x = np.linspace(-2, 2, 100)

# define a function to apply to the x values
f2 = lambda i: i**2

# calculate our y values
f2y = f2(x)
© www.soinside.com 2019 - 2024. All rights reserved.