is there a neat way to include conditions in list comprehensions in order to do the following:
index = [y for y, s in enumerate(data_time_filtered) if next0 in s]
I'd like to add the following conditions in the index definition above:
if next0 in s:
data_filtered.append(data_time_filtered[index[0]])
else:
missing_data.append(next0)
currently what's happening in my code is:
IndexError: list index out of range
when the value can not be found. Is it more efficient to handle it with else and if conditions or is there another / better way for error handling in this case?
EXTENSION:
data_time_filtered
is a list of strings like:
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.A2018002.1330.006.2018003152138.hdf
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/004/MYD021KM.A2018004.1330.006.2018005220236.hdf
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/006/MYD021KM.A2018006.1330.006.2018007165439.hdf
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/009/MYD021KM.A2018009.1330.006.2018010190624.hdf
next0
are strings in the form of: /XXX/
for example /002/
The index function is looking for the line in data_time_
filtered where next0
appears and is returning a index which is used in order to extract that line and append it to a different list.
The problem is that sometimes, the string given by next0
is not contained in the list creating the error message above.
What I would like is:
If index comes a cross such a number it should append this number in a missing_data
list instead of breaking and producing the error.
UPDATE:
i tried this:
try:
index = [y for y, s in enumerate(data_time_filtered) if next0 in s]
data_filtered.append(data_time_filtered[index[0]])
except IndexError:
missing_data.append(next0)
and it worked :). However, in a later stage on a different line an IndexError is occurring. still checking how to sort this out