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?
列出理解。
list_2 = [num for num in list_1 if isinstance(num, (int,float))]
This should be the most efficient and shortest in Python 2:
import operator
filter(operator.isNumberType, list_1)
This in Python 3:
import numbers
[x for x in list_1 if isinstance(x, numbers.Number)]
list_2 = [i for i in list_1 if isinstance(i, (int, float))]
All solutions proposed work only if the numbers inside the list are already converted to the appropriate type ( int
, float
).
I found myself with a list coming from the fetchall
function of sqlite3
. All elements there were formated as str
, even if some of those elements were actually integers.
cur.execute('SELECT column1 FROM table1 WHERE column2 = ?', (some_condition, ))
list_of_tuples = cur.fetchall()
The equivalent from the question would be having something like:
list_1 = [ 'asdada', '1', '123131', 'blaa adaraerada', '0', '34', 'stackoverflow is awesome' ]
For such a case, in order to get a list with the integers only, this is the alternative I found:
list_of_numbers = []
for tup in list_of_tuples:
try:
list_of_numbers.append(int(tup[0]))
except ValueError:
pass
list_of_numbers will contain only all integers from the initial list.
I think the easiest way is:
[s for s in myList if s.isdigit()]
Hope it helps!
filter(lambda n: isinstance(n, int), [1,2,"three"])
list_2 = [i for i in list_1 if isinstance(i, (int, float))]
>>> [ i for i in list_1 if not str(i).replace(" ","").isalpha() ]
[1, 123131.13099999999, 9.9999999999999995e-07, 34.124512352650001]
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)]
list_1 = [ 'asdada', 1, 123131.131, 'blaa adaraerada', 0.000001, 34.12451235265, 'stackoverflow is awesome' ]
first example:
list_2 = [x for x in list_1 if type(x) == int or type(x) == float ]
print(list_2)
second example:
list_2 = [x for x in list_1 if isinstance(x, (int, float)) ]
print(list_2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.