我是 Python 新手。我有一個二維陣列(10,4),需要通過將每行的四個值分配給函式的四個變數(x1、x2、x3、x4)來迭代陣列元素,并回傳函式輸出。請查看我的代碼并給我合適的建議。謝謝
import pandas as pd
import numpy as np
nv = 4
lb = [0, 0, 0, 0]
ub = [20, 17, 17, 15]
n = 10
def random_population(nv,n,lb,ub):
pop = np.zeros((n, nv))
for i in range(n):
pop[i,:] = np.random.uniform(lb,ub)
return pop
population = random_population(nv, n, lb, ub)
i = 0 #row number
j = 0 # col number
rows = population.shape[0]
cols = population.shape[1]
x1 = population[i][j]
x2 = population[i][j 1]
x3 = population[i][j 2]
x4 = population[i][j 3]
def test(x1, x2, x3, x4):
##Assignment statement
y = x1 x2 x3 x4
return y
test(x1, x2, x3, x4)
uj5u.com熱心網友回復:
您可以使用 Python 星形運算式將陣列作為引數串列傳遞給您的測驗函式。
test(*population[i])
// instead of
x1 = population[i][j]
x2 = population[i][j 1]
x3 = population[i][j 2]
x4 = population[i][j 3]
test(x1, x2, x3, x4)
uj5u.com熱心網友回復:
原來你可以給你的函式numpy陣列,因為它們之間的加法被定義為元素加法,它可以滿足你的需求。所以你首先像這樣從陣列中提取列
population[:,0], population[:,1], ...
然后
test(population[:,0],population[:,1],population[:,2],population[:,3])
給你一個陣列,第一個值同意
test(x1, x2, x3, x4).
uj5u.com熱心網友回復:
問題尚不清楚,但如果我的目標正確,并且作者只需要根據標題進行迭代(而不是Michael Szczesny 在評論中提到的矢量化),則以下回圈會將人口陣列的每一行放入測驗功能:
for row in population:
x1, x2, x3, x4 = row
test(x1, x2, x3, x4)
要么
for row in population:
test(*row)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454678.html
上一篇:如何將嵌套陣列串列轉換為陣列
