Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

python: extract integers from mixed list

(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:

testList = [1, 4.66, 7, "abc", 5, True, 3.2, False, "Hello", 7]

I thought this would be simple, and just wrote:

def parseIntegers(mixedList):
    newList = [i for i in mixedList if isinstance(i, int)]
    return newList

Problem is that the newList this creates has boolean values as well as integers, meaning it gets me:

[1, 7, 5, True, False, 7]

Why is that? I also used for loop (for i in mixedList: if isinstace.....), but it's essentially the same(?) and has the same problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...