【问题标题】:python: extract integers from mixed listpython:从混合列表中提取整数
【发布时间】:2014-11-04 08:31:21
【问题描述】:

(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]

这是为什么呢?我也用过for循环(for i in mixedList: if isinstace.....),但本质上是一样的(?),也有同样的问题。

【问题讨论】:

  • 改用type(i) == int。
  • 小心使用type - 这打破了多态性的概念:如果有人继承int,你的代码将不再工作。
  • @Smashery 看来他们不想在这种情况下包含子类。
  • 可能是这样 - 但如果您试图规避面向对象语言的关键特性(多态性),您最好知道自己在做什么。也许使用type 是正确的做法。只是要小心。
  • @Smashery 这里的问题是bool 是 int 的一个子类并且它是不需要的,所以打破isinstance 准则并使用type 是在这种情况下是正确的。

标签: python


【解决方案1】:

显然 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
>>> 

您可以使用type(i) is int 或isinstance(i, int) and not isinstance(i, bool),而不是isinstance(i, int)。

【讨论】:

    【解决方案2】:

    正如@pts 对isinstance 的解释,所以像这样使用type

    [ x for x in testList if type(x)==int ]
    

    输出:

    [1, 7, 5, 7]
    

    使用set 删除重复项

    【讨论】:

      【解决方案3】:

      最好的方法不是使用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
      

      【讨论】:

      【解决方案4】:
      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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        相关资源
        最近更新 更多