Filter a list in python get integers

前端 未结 4 1897
花落未央
花落未央 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

    Use list comprehension

    >>> t = ['Jack', 18, 'IM-101', 99.9]
    >>> [x for x in t if type(x) == type(1)]
    [18]
    >>> 
    

    map(int, x) throws an error

    map function applies int(t) on every element of x.

    This throws an error because int('Jack') will throw an error.

    [Edit:]

    Also isinstance is purer way of checking that it is of type integer, as sukhbir says.

提交回复
热议问题