Is there a way to output the numbers only from a python list?

后端 未结 10 1434
情歌与酒
情歌与酒 2020-12-11 02:15

Simple Question:

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

I want

相关标签:
10条回答
  • 2020-12-11 02:19

    List comprehensions.

    list_2 = [num for num in list_1 if isinstance(num, (int,float))]
    
    0 讨论(0)
  • 2020-12-11 02:22
    list_2 = [i for i in list_1 if isinstance(i, (int, float))]
    
    0 讨论(0)
  • 2020-12-11 02:23

    I think the easiest way is:

    [s for s in myList if s.isdigit()]
    

    Hope it helps!

    0 讨论(0)
  • 2020-12-11 02:25

    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.

    0 讨论(0)
  • 2020-12-11 02:26

    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)]
    
    0 讨论(0)
  • 2020-12-11 02:27
    filter(lambda n: isinstance(n, int), [1,2,"three"])
    
    0 讨论(0)
提交回复
热议问题