List comprehension replacing items that are not float or int

后端 未结 5 603
一个人的身影
一个人的身影 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:21

    This looks more like a true list comprehension way to do what you want...

    def isfloat(string):
        try:
            float(string)
            return True
        except:
            return False
    
    [float(item) for s in mylist for item in s.split() if isfloat(item)]
    #[10000.0, 5398.38770002321]
    

    Or remove the float() to get the items as strings. You can use this list comprehension only if '>' or '<' are found in the string.

提交回复
热议问题