python - Removing items from list if argument is False -
my code check if time valid, returns list true , false, depends, want if it's false remove list.
here's code
def markvalid(s): = [] if len(s) > 2: if s[1] - s[0] > 0.1: a.append(true) else: a.append(false) in range(1, len(s) - 1): if s[i] - s[i - 1] < 0.1 or s[i + 1] - s[i] < 0.1: a.append(false) else: a.append(true) if s[-1] - s[-2] > 0.1: a.append(true) else: a.append(false) return if len(s) == 1: return [true] if len(s) == 2 , s[1] - s[0] > 0.1: return [true, true] else: return [false, false]
just don't append false
s?
however if understand correctly, want filter input list, right? if case can use current function 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 x,m in zip(test,markvalid(test)) if m] [5.1, 5.6, 6.0, 12.5] >>>
if not case, here alternative filter
>>> [x x in markvalid(test) if x ] [true, true, true, true] >>>
in case of filtering data can same effect original function instead of appending true append value in position i
, nothing otherwise, , in others cases return original list or empty list accordingly, minor changes code
def filtervalid(s): if len(s) > 2: a=[] if s[1] - s[0] > 0.1: a.append(s[0]) in range(1, len(s) - 1): if not( s[i] - s[i - 1] < 0.1 or s[i + 1] - s[i] < 0.1 ): a.append(s[i]) if s[-1] - s[-2] > 0.1: a.append(s[-1]) return if len(s) == 1: return s if len(s) == 2 , s[1] - s[0] > 0.1: return s return []
and testing it
>>> filtervalid(test) [5.1, 5.6, 6.0, 12.5] >>>
Comments
Post a Comment