我有这段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次。我该怎么做?
答案 0 :(得分:3)
您可以使用itertools.chain.from_iterable
和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
答案 1 :(得分:0)
您在寻找:
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
答案 2 :(得分:0)
这可以满足您的要求:
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_timeafter
时,请记住使用单引号cldsat_timebefore
。