tags:

views:

221

answers:

7

Simple Question:

list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]

I want to create a list_2 such that it only contains the numbers:

list_2 = [ 1, 123131.131, 0.000001, 34.12451235265 ]

Is there simplistic way of doing this, or do I have to resort to checking the variable type of each list item and only output the numerical ones?

A: 
filter(lambda n: isinstance(n, int), [1,2,"three"])
Jeff Ober
To test for various types:filter(lambda n: isinstance(n, int) or isinstance(n, float), list_of_values)
Jeff Ober
i meant numbers in general and not just ints
dassouki
+11  A: 

List comprehensions.

list_2 = [num for num in list_1 if isinstance(num, (int,float))]
Ants Aasma
that worked great, thanks :D
dassouki
It may be worth adding the type long to your tuple.
Corey D
To improve this, you can use operator.isNumberType to determine if an element is a number (see my other answer, to do this with filter instead of a list comprehension).
dalloliogm
A: 
list_2 = [i for i in list_1 if isinstance(i, (int, float))]
sykora
`isinstance` takes only 2 arguments.
SilentGhost
Probably meant: list_2 = [i for i in list_1 if isinstance(i, (int, float))]
hughdbrown
Ah. Fixed.
sykora
+2  A: 
list_2 = [i for i in list_1 if isinstance(i, (int, float))]
SilentGhost
A: 
>>> [ i for i in list_1 if not str(i).replace(" ","").isalpha() ]
[1, 123131.13099999999, 9.9999999999999995e-07, 34.124512352650001]
ghostdog74
that would be **very** slow
SilentGhost
+12  A: 

This should be the most efficent and shortest:

import operator
filter(operator.isNumberType, list_1)

Edit: this in python 3000:

import numbers
[x for x in list_1 if isinstance(x, numbers.Number)]
dalloliogm
won't work in py3k
SilentGhost
I don't use py3k, but then it will be just isinstance(x, numbers.Number) instead of operator.isNumberType)
dalloliogm
ok.. I don't know much of python 3k, so I have changed the example again.
dalloliogm
A: 

for short of SilentGhost way

list_2 = [i for i in list_1 if isinstance(i, (int, float))]

to

list_2 = [i for i in list_1 if not isinstance(i, str)]
bugbug