Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 894
01110100 Avatar asked Jan 01 '13 18:01

01110100


People also ask

How do you set a specific data type in Python?

Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by 'comma'. Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set.

How do you write a conditional statement in Python?

The statement can be a single line or a block of code. #If the condition is true, the statement will be executed. num = 5 if num > 0: print(num, "is a positive number.") print("This statement is true.") #When we run the program, the output will be: 5 is a positive number. This statement is true.


1 Answers

How about,

if isinstance(x, int): 

but a cleaner way would simply be

sum(z for z in y if isinstance(z, int)) 
like image 181
Jakob Bowyer Avatar answered Sep 19 '22 19:09

Jakob Bowyer