你如何根据数据类型在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):
但更简洁的方法就是
sum(z for z in y if isinstance(z, int))
这篇关于你如何根据数据类型在python中设置条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文