Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty element but keep zeros as values

Tags:

python

list

I have a list as follows:

lst = [-1.33, '', -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0, 0, 1.40, '',  1.37, 0]

where there are two empty elements '' in the list with several zeroes and float numbers.

How can I remove the empty elements but keep the zeroes? as follows...

lst2 = [-1.33, -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0, 0, 1.40, 1.37, 0]   

I have tried the following:

lst2 = filter(None, lst)

and

lst2 = [x for x in lst if x if isinstance(x,str) == False]

but, it removes the zeroes as well.

I know floats return 12 decimal places, please ignore for example purposes.

Any advice? Thanks.

like image 301
siva Avatar asked Apr 17 '26 05:04

siva


2 Answers

Why not simply remove all '' ?

>>> lst2 = [x for x in lst if x != '']
>>> lst2
[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]
>>>

or you could keep only floats and ints:

>>> [x for x in lst if isinstance(x, (float, int))]
[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]

# or a bit fancier
>>> import numbers
>>> [x for x in lst if isinstance(x, numbers.Number)]
[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]
like image 99
Jochen Ritzel Avatar answered Apr 18 '26 18:04

Jochen Ritzel


Let's take a look at what you have

lst2 = [x for x in lst 
if x 
if isinstance(x,str) == False]

What do you have the if x in there for?

Also, never never never use == False and == True

Use not isinstance(x, str)

So you should have

   lst2 = [x for x in lst if isinstance(x, str)]

Or as other have suggested

lst2 = [x for x in lst if x != '']

Since your list has both strings and numbers in it, I suspect that it'll be easier to deal this at the point that you created this list. Of course, without seeing that I can't be certain or tell you how to fix it.

like image 23
Winston Ewert Avatar answered Apr 18 '26 18:04

Winston Ewert



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!