Warm tip: This article is reproduced from serverfault.com, please click

How do you set a conditional in python based on datatypes?

发布于 2013-01-01 18:45:00

This question seems mind-boggling simple, yet I can't figure it out. I know you can check datatypes in python, but how can you set a conditional based on the datatype? For instance, if I have to write a code that sorts through a dictionary/list and adds up all the integers, how do I isolate the search to look for only integers?

I guess a quick example would look something like this:

y = []
for x in somelist:
    if type(x) == <type 'int'>:  ### <--- psuedo-code line
    y.append(x)
print sum(int(z) for z in y)

So for line 3, how would I set such a conditional?

Questioner
01110100
Viewed
0
Jakob Bowyer 2013-01-02 02:46:08

How about,

if isinstance(x, int):

but a cleaner way would simply be

sum(z for z in y if isinstance(z, int))