Blue Monday Blue Monday - 1 year ago 61
Python Question

Removing items from list if argument is False

My code is to check if the time is valid, it returns list with True and False, depends, however I want if it's False to remove it from the list.

Here's my code

def markValid(s):
a = []
if len(s) > 2:
if s[1] - s[0] > 0.1:
for i in range(1, len(s) - 1):
if s[i] - s[i - 1] < 0.1 or s[i + 1] - s[i] < 0.1:
if s[-1] - s[-2] > 0.1:
return a
if len(s) == 1:
return [True]
if len(s) == 2 and s[1] - s[0] > 0.1:
return [True, True]
return [False, False]

Answer Source

just don't append the Falses?

however if I understand correctly, you want to filter your input list, right? If that is the case you can use your current function for that like

>>> test=[5.1, 5.6, 6.0, 10.34, 10.37, 10.45, 12.5]
>>> markValid(test)
[True, True, True, False, False, False, True]
>>> [x for x,m in zip(test,markValid(test)) if m]
[5.1, 5.6, 6.0, 12.5]

if that is not the case, here is an alternative to filter

>>> [x for x in markValid(test) if x ]
[True, True, True, True]

In the case of filtering your data you can also get the same effect with your original function by instead of appending True append the value in position i and do nothing otherwise, and in the others cases return the original list or a empty list accordingly

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download