如何根据数据类型在python中设置条件?

如何根据数据类型在python中设置条件?

问题描述:

这个问题似乎让人难以置信,但我无法弄清楚。我知道您可以在python中检查数据类型,但是如何根据数据类型设置条件呢?例如,如果我必须编写一个对字典/列表进行排序并将所有整数加起来的代码,那么如何隔离搜索以仅查找整数?

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)

因此,对于第3行,我将如何设置这样的条件?

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

怎么样,

if isinstance(x, int):

,但是更简洁的方法将是

but a cleaner way would simply be

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