遍历 for 循环

Iterating over for loops

我有这段Python代码:

time =  ['0115','0215','0315','0715','0815','0915','1015']
N_profiles_select = 582
cldsat_timeafter = 0815
cldsat_timebefore = 0115

if time < cldsat_timeafter and time > cldsat_timebefore:  
    for i in range(N_profiles_select):  
        print time

现在第一次打印(0215)582次,第二次(0315)打印582次,第三次打印582次。

我想要它做的是按以下顺序打印时间:

0215,0315,0715, 0215,0315,0715

然后这三个数字将重复 582 次。我该怎么做?

您在寻找:

for i in range(N_profiles_select):
    for t in time:
        if t < cldsat_timeafter and t > cldsat_timebefore:
            print t

(只是改变了 for 循环的顺序)

这只是为了说明逻辑。但是您最好确定要一劳永逸地打印 time 的哪些元素,而不是测试它 N_profiles_select 次。

你会做:

selectedTimes = [t in time if t < cldsat_timeafter and t > cldsat_timebefore]
for i in range(N_profiles_select):
    for t in selectedTimes:
        print t

这给出了你所要求的:

time =  ['0115','0215','0315','0415','0615','0715','0815','0915','1015']
N_profiles_select = 582
cldsat_timeafter = '0815'
cldsat_timebefore = '0115'

for i in range(N_profiles_select):
    for t in time:
        if t < cldsat_timeafter and t > cldsat_timebefore:
            print t

打印:

0215
0315
0415
0615
0715

N_profiles_select

PS:记得在设置值cldsat_timeaftercldsat_timebefore.[=16时使用单引号' =]

您可以使用 itertools.chain.from_iterable and itertools.repeat 来避免多次迭代列表:

from itertools import chain, repeat

time =  ['0115','0215','0315','0715','0815','0915','1015']
N_profiles_select = 582
cldsat_timeafter = '0815'
cldsat_timebefore = '0115'

filtered_elements = [x for x in time if cldsat_timebefore < x < cldsat_timeafter]
for elem in chain.from_iterable(repeat(filtered_elements, N_profiles_select)):
    print elem