【问题标题】:Python - Identifying Extraneous Types within a ListPython - 识别列表中的无关类型
【发布时间】:2016-08-02 14:47:25
【问题描述】:

假设我有一个表示数值矩阵的二维列表(不,我没有为此使用 numPy)。此列表中允许的类型属于numbers.Number 类别。假设我希望隔离此列表中的任何非数字值,例如字符串,我能看到的唯一选择是单独检查每个元素并检查它是否不是数字的实例。数字:

from numbers import Number

def foo(matrix):
   # Check for non-numeric elements in matrix
   for row in matrix:
      for element in row:
         if not isinstance(element, Number):
            raise ValueError('The Input Matrix contains a non-numeric value')
   ...

我的问题是:是否有另一种方法可以在不查看每个元素的情况下检查整个矩阵? Python 或其库之一是否具有用于识别列表(列表)中无关元素的内置函数?还是应该继续我提供的当前示例?

【问题讨论】:

    标签: python list matrix elements isinstance


    【解决方案1】:

    试试这个:

    print(any(not isinstance(x, Number) for row in matrix for x in row))
    

    并在函数中:

    def foo(matrix):
        if any(not isinstance(x, Number) for row in matrix for x in row):
            raise ValueError('The Input Matrix contains a non-numeric value')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      相关资源
      最近更新 更多