我有一段代碼,我想在連續回圈迭代中過濾掉串列的一部分:
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
我在這里做錯了什么?
uj5u.com熱心網友回復:
當您遍歷 zip 物件時,它會彈出所有資料,因此第二次這是一個空串列,samples_filtered = [s for s in samples if s[0] >= flash_time_stamp]因此您可以像這樣隨時隨地壓縮資料:
samples_filtered = [s for s in zip(sample_time_stamps, sample_values) if s[0] >= flash_time_stamp]
uj5u.com熱心網友回復:
我什至不會在這里使用串列理解,第二個片段會更有效,因為如果第一個元素讓您盡早中斷回圈,您不會不必要地創建串列。
您可以使用 next 并完全替換整個 for 回圈
first_cross_thresh_time_stamp = next(
(s[0] for s in samples if s[0] >= flash_time_stamp and s[1] < threshold),
-1
)
first_thresh_cross_time_stamps.append(first_cross_thresh_time_stamp)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/384599.html
上一篇:訪問字典中的資料框
