【问题标题】:Count all numbers from matrix list in python [duplicate]计算python中矩阵列表中的所有数字[重复]
【发布时间】:2021-09-03 13:56:30
【问题描述】:
def count(matrix: list, number: int):

    count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)

我正在尝试创建计算矩阵列表中的所有零或任何其他数字但现在为 0 的函数。

【问题讨论】:

标签: python list function matrix counting


【解决方案1】:

试试这个:

def count(matrix: list, number: int):
    return sum(l.count(number) for l in matrix)

count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)
# 9

count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 6)
# 2

【讨论】:

    【解决方案2】:
    import itertools
    def count(matrix: list, number: int):
        return list(itertools.chain.from_iterable(matrix)).count(number)
        
    count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)
    

    9

    【讨论】:

      猜你喜欢
      • 2013-12-30
      • 2013-03-15
      • 2014-02-09
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2018-02-23
      相关资源
      最近更新 更多