List comprehension replacing items that are not float or int

后端 未结 5 561
一个人的身影
一个人的身影 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.

    0 讨论(0)
  • 2021-01-17 02:29

    If you want to edit the list in place rather than create a new list, you can iterate over it using enumerate:

    for (list_index, item) in enumerate(values):
        if '> ' in item:
            values[list_index] = ' '.join(item_part for item_part in item.split() if is_number(item_part))
    

    Or however you want to construct your new value - I'm not sure what you want if you have '5 6' in your original list.

    If you want a new list, you can do something similar with a list comprehension.

    0 讨论(0)
  • 2021-01-17 02:30

    Iterators work well here:

    def numbers_only(l):
        for item in l:
            if '> ' in item:
                item = item.split()[1]
            try:
                yield float(item)
            except ValueError:
                pass
    
    >>> values = ['> 10000', '5398.38770002321']
    >>> list(numbers_only(values))
    [10000.0, 5398.38770002321]
    

    Normally, it's easier to create a new list than it is to iterate and modify the old list

    0 讨论(0)
  • 2021-01-17 02:31

    What about

    def stip_chars(lst):
        for item in lst:
            yield item.strip("> ")
    
    new_values = [v for v in strip_chars(values) if is_number(v)]
    

    ?

    0 讨论(0)
  • 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.-'

    0 讨论(0)
提交回复
热议问题