[英]Is there any way to apply a function to an array of lists in pyhton?
我有一個包含兩個坐標的列表數組。 我想申請這個function:
def f(x, y, a, b):
return sign(y - a*x - b)
其中x和y為坐標,a和b定義直線方程。
function 返回線與點之間距離的符號。
有沒有辦法立即將這個 function 應用於列表數組並獲得 label 列表? 喜歡:
Y = f(x[:,0],x[:,1],a,b)
謝謝
你可以使用 numpy vectorize
:
vectorize
define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns a single numpy array or a tuple of numpy arrays. The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it使用numpy的廣播規則。
def f(x, y, a, b):
return np.sign(y - a*x - b)
vfunc = np.vectorize(f)
output:
x = np.random.rand(10,10)
y = np.random.rand(10,10)
Y = vfunc(x[:,0],y[:,1],1,0)
print(Y)
>> [-1. 1. 1. -1. -1. -1. -1. 1. -1. -1.]
你的意思是map()
, map 為 iterable 的每個元素調用 function
例如:
def f(x):
return x**2
lst = [1,2,3,4,5]
print(tuple(map(f, lst)))
Output:
(1,4,9,16,25)
*非常重要的map返回生成器,所以需要使用tuple()
或list()
從map獲取值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.