python: extract integers from mixed list

前端 未结 4 811
无人及你
无人及你 2020-12-22 12:02

(python 2.7.8)

I\'m trying to make a function to extract integers from a mixed list. Mixed list can be anything but the e.g. I\'m going with is:

test         


        
相关标签:
4条回答
  • 2020-12-22 12:46

    as explained by @pts for isinstance, so use type like this

    [ x for x in testList if type(x)==int ]
    

    output:

    [1, 7, 5, 7]
    

    use set to remove duplication

    0 讨论(0)
  • 2020-12-22 12:49
    testList = [1, 4.66, 7, "abc", 5, True, 3.2, False, "Hello", 7]
    print([x for x in testList if isinstance(x,int) and not isinstance(x,bool)])
    [1, 7, 5, 7]
    
    0 讨论(0)
  • 2020-12-22 12:50

    The best approach is not to use type, but to use a chain of isinstance calls. The pitfall of using type is that someone could subclass int in the future, and then your code won't work. Also, since you are using Python 2.x, you need to consider numbers greater than or equal to 2^31: these are not ints. You need to consider the long type:

    def parseIntegers(mixedList):
        return [x for x in testList if (isinstance(x, int) or isinstance(x, long)) and not isinstance(x, bool)]
    

    Reason for needing to consider long:

    >>> a = 2 ** 31
    >>> isinstance(a, int)
    False
    
    0 讨论(0)
  • 2020-12-22 13:02

    Apparently bool is a subclass of int:

    Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> isinstance(42, int)
    True
    >>> isinstance(True, int)
    True
    >>> isinstance('42', int)
    False
    >>> isinstance(42, bool)
    False
    >>> 
    

    Instead of isinstance(i, int), you can use type(i) is int or isinstance(i, int) and not isinstance(i, bool).

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