Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete list elements based on condition in Python

Tags:

python

list

I have following 2D array in python

[[(0, 0, 0), 337.94174378689814],
[(0, 0, 1), 339.92776762374007],
[(0, 0, 2), 338.78632729456444],
[(0, 1, 0), 344.85997106879347],
[(0, 1, 1), 331.6819890120493],
[0, 0]]

I want to delete elements which has 0 values in it The output is ARIMA order and corresponding AIC score which I generate from following code

a = [[0]*2 for x in range(27)]

for i in range(len(pdq)):
   try:
      mod =  ARIMA(train, order = pdq[i]) 
      results = mod.fit(disp=False)
      a[i][0] = pdq[i]
      a[i][1] = results.aic
      if a[i][1] == 0:
         a.remove(a[i])
   except:
       continue

I want to delete values in array where there are both 0. How can I do it in if condition described above

like image 649
Neil Avatar asked Feb 16 '26 10:02

Neil


2 Answers

I assume you have a regular Python list, not a NumPy np.ndarray.

It's tempting to think that an in-place solution will be more efficient than creating a new list. This isn't really the case, O(n) complexity can't be beaten as you'll need to check each element at least once.

So you can use a list comprehension for this:

res = [i for i in L if i != [0, 0]]

Indeed, repeated list.remove calls will be inefficient: each list.remove call has O(n) time complexity.

like image 125
jpp Avatar answered Feb 18 '26 23:02

jpp


If you just want to delete [0,0] you can do it like this:

a = [[(0, 0, 0), 337.94174378689814],
     [(0, 0, 1), 339.92776762374007],
     [(0, 0, 2), 338.78632729456444],
     [(0, 1, 0), 344.85997106879347],
     [(0, 1, 1), 331.6819890120493],
     [0, 0]]

while True:
    try:
        a.remove([0, 0])
    except ValueError:
        break

Or use filter:

a = list(filter(lambda x: x != [0, 0], a))
like image 22
James Liu Avatar answered Feb 19 '26 00:02

James Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!