gpt4 book ai didi

python - 如何摆脱 Python 代码中的嵌套 for 循环?

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:22 24 4
gpt4 key购买 nike

我对电子进行了 1 年的卫星测量(仪器每 4 秒测量一次)。该阵列称为“电子”。我也有格式为 datetime.datetime 的相应时间(称为“时间”)。我想平均电子阵列以获得每分钟而不是每 4 秒的平均值。我想把它们放在一个新数组“g”中。但是,当我编写循环时,它变得非常慢。有什么办法让它更快吗?这是我所做的:

import numpy as np
import spacepy.time as spt
import datetime as dt

year=2001
for month in range (1,13):
dmax=np.array([[31,28,31,30,31,30,31,31,30,31,30,31]]).T #number of days in a month
for day in range(1,dmax[month-1]+1):
for hour in range(24):
for minute in range(60):

D1=spt.Ticktock(dt.datetime(year, month, day, hour, minute, 0,0),'UTC').RDT #lower boundary of a minute

#here, spt is a spacepy.time, and '.RDT' returns GREGORIAN ORDINAL TIME.

D2=spt.Ticktock(dt.datetime(year, month, day, hour, minute, 59,999999),'UTC').RDT #upper boundary of a minute

mask=((time>D1)&(time<D2))

electrons_logic=electrons[mask]
k=(month-1)*dmax[month-1]*24*60+(day-1)*24*60+hour*60+(minute+1) #number of the minute in a year
g[k,0]=np.nanmean(electrons_logic)

有没有办法避免嵌套循环并使其更快?

也许有一种方法可以使用多处理/并行计算使其更快?

最佳答案

每当你遇到关于迭代的问题时,想想itertools .

from itertools import product

dmax=np.array([[31,28,31,30,31,30,31,31,30,31,30,31]]).T
for month in range (1,13):
for day, hour, minute in product(range(1,dmax[month-1]+1), range(24), range(60)):
...

我还建议在循环外定义 dmax,否则它会在每次 month 迭代时实例化。

关于python - 如何摆脱 Python 代码中的嵌套 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50955427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com