Filter a list in python get integers

前端 未结 4 1892
花落未央
花落未央 2020-11-30 14:48

I have a list:

[\'Jack\', 18, \'IM-101\', 99.9]

How do I filter it to get only the integers from it??

I tried

map(i         


        
4条回答
  •  孤独总比滥情好
    2020-11-30 15:38

    In case the list contains integers that are formatted as str, the list comprehension would not work.

    ['Jack', '18', 'IM-101', '99.9']
    

    I figured out the following alternative solution for that case:

    list_of_numbers = []
    for el in your_list:
        try:
            list_of_numbers.append(int(el))
        except ValueError:
            pass
    

    You can find more details about this solution in this post, containing a similar question.

提交回复
热议问题