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

后端 未结 10 1435
情歌与酒
情歌与酒 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:36
    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)
    
    0 讨论(0)
  • 2020-12-11 02:36
    >>> [ i for i in list_1 if not str(i).replace(" ","").isalpha() ]
    [1, 123131.13099999999, 9.9999999999999995e-07, 34.124512352650001]
    
    0 讨论(0)
  • 2020-12-11 02:41

    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)]
    
    0 讨论(0)
  • 2020-12-11 02:41
    list_2 = [i for i in list_1 if isinstance(i, (int, float))]
    
    0 讨论(0)
提交回复
热议问题