如何根据数据类型在python中设置条件? [英] How do you set a conditional in python based on datatypes?
本文介绍了如何根据数据类型在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))
这篇关于如何根据数据类型在python中设置条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文