【发布时间】:2022-01-16 18:44:44
【问题描述】:
我有一段代码,我想在连续循环迭代中过滤掉列表的一部分:
def calculate_delays(flash_time_stamps, sample_time_stamps, sample_values, threshold):
delays = []
first_thresh_cross_time_stamps = []
samples = zip(sample_time_stamps, sample_values)
# For each flash find the first sample that crosses the chosen threshold
# and calculate the difference between the corresponding timestamps
for flash_time_stamp in flash_time_stamps:
first_cross_thresh_time_stamp = -1
# Ignore samples that occured before the flash
samples_filtered = [s for s in samples if s[0] >= flash_time_stamp] # ---COMPREHENSION IS HERE---
for sample in samples_filtered:
if sample[1] < threshold:
first_cross_thresh_time_stamp = sample[0]
break
# Save
first_thresh_cross_time_stamps.append(first_cross_thresh_time_stamp)
delays.append(first_cross_thresh_time_stamp - flash_time_stamp)
return first_thresh_cross_time_stamps, delays
在第一次迭代中,代码按预期工作,但在随后的迭代中,列表推导返回一个空列表。根据我传递的数据,我知道这不应该是这种情况。此外,以下代码按预期工作:
def calculate_delays(flash_time_stamps, sample_time_stamps, sample_values, threshold):
delays = []
first_thresh_cross_time_stamps = []
samples = zip(sample_time_stamps, sample_values)
# For each flash find the first sample that crosses the chosen threshold
# and calculate the difference between the corresponding timestamps
for flash_time_stamp in flash_time_stamps:
first_cross_thresh_time_stamp = -1
# Ignore samples that occured before the flash
for sample in samples:
if sample[0] < flash_time_stamp: # ---CHANGE HERE---
continue
if sample[1] < threshold:
first_cross_thresh_time_stamp = sample[0]
break
# Save
first_thresh_cross_time_stamps.append(first_cross_thresh_time_stamp)
delays.append(first_cross_thresh_time_stamp - flash_time_stamp)
return first_thresh_cross_time_stamps, delays
我在这里做错了什么?
【问题讨论】:
标签: python loops list-comprehension