List comprehension replacing items that are not float or int

后端 未结 5 563
一个人的身影
一个人的身影 2021-01-17 02:21

I have a 2 item list.

Sample inputs:

[\'19(1,B7)\', \'20(1,B8)\']
[\'16 Hyp\', \'16 Hyp\']
[\'< 3.2\', \'38.3302615548213\']
[\'18.6086945477694\         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 02:44

    values = ['> 10000', '5398.38770002321']
    print [filter(lambda s: s in '0123456789.', v) for v in values]
    

    RETURNS:

    ['10000', '5398.38770002321']
    

    List of strings, as requested.

    And to make it a function:

    def parse_number(value):
        return [filter(lambda s: s in '0123456789.', v) for v in values]
    
    print parse_number(values)
    

    As an added bonus, making this accept negative numbers would be as easy as adding a hyphen to the whitelisted string '0123456789.-'

提交回复
热议问题