如何为每个单独的数组创建一个 for 循环?

How do I make a for loop to each individual array?

我创建了一个函数,我希望使用 for 循环或其他方式将该函数应用于这些不同的值。 如何创建一个 for 循环来获取每个值并将它们存储在不同的数组中?

到目前为止我有这个:

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.patches as patches 
import xarray as xr 
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import netCDF4 as s
import numpy.ma as ma

fwf_tot = fwf_ice      + ds.runoff_tundra*ds.LSMGr #data input i am using 


# function i want to apply to the data

def ob_annual(ob_monthly, id_number):
    ann_sum =  ob_monthly.where(ds.ocean_basins == id_number).resample(TIME='1AS').sum().sum(dim=('X','Y'))
    return ann_sum 

我的问题是创建 for 循环以保存这些不同的值。我认为这个 for 循环只是保存应用于最后一个值 (87) 而不是其他值的函数。我该如何解决这个问题?我预计会有 7 个数组的输出,每个数组的大小为 59。

obs = np.array([26,28,29,30,76,84,87])

total_obs = []

for i in obs:
    total_obs = ob_annual(fwf_tot_grnl, i)
    
print(total_obs.shape) 

(59)

您在每次迭代时替换您的列表 total_obs。您必须将每个值附加到其中:

for i in obs:
    total_obs.append(ob_annual(fwf_tot_grnl, i))

或使用理解列表

total_obs = [ob_annual(fwf_tot_grnl, i) for i in obs]