[英]python: extract integers from mixed list
(python 2.7.8)
我正在尝试使函数从混合列表中提取整数。 混合列表可以是任何东西,但是我要使用的是:
testList = [1, 4.66, 7, "abc", 5, True, 3.2, False, "Hello", 7]
我以为这很简单,所以写道:
def parseIntegers(mixedList):
newList = [i for i in mixedList if isinstance(i, int)]
return newList
问题是它创建的newList具有布尔值和整数,这意味着它使我明白了:
[1, 7, 5, True, False, 7]
这是为什么? 我也用于循环(对于mixedList中的i:if isinstace .....),但它本质上是相同的(?),并且存在相同的问题。
显然bool是int的子类:
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(42, int)
True
>>> isinstance(True, int)
True
>>> isinstance('42', int)
False
>>> isinstance(42, bool)
False
>>>
代替isinstance(i, int)
,可以使用type(i) is int
或isinstance(i, int) and not isinstance(i, bool)
。
如通过对@pts解释isinstance,所以使用type
这样
[ x for x in testList if type(x)==int ]
输出:
[1, 7, 5, 7]
使用set
删除重复项
最好的方法不是使用type
,而是使用isinstance
调用链。 使用type
的陷阱是,将来有人可以继承int
,然后您的代码将无法工作。 另外,由于您使用的是Python 2.x,因此需要考虑大于或等于2 ^ 31的数字:这些不是整数。 您需要考虑long
类型:
def parseIntegers(mixedList):
return [x for x in testList if (isinstance(x, int) or isinstance(x, long)) and not isinstance(x, bool)]
需要考虑long
原因:
>>> a = 2 ** 31
>>> isinstance(a, int)
False
testList = [1, 4.66, 7, "abc", 5, True, 3.2, False, "Hello", 7]
print([x for x in testList if isinstance(x,int) and not isinstance(x,bool)])
[1, 7, 5, 7]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.