Python 程序使用 map 函数查找 1 数量最多的行
programmingpythonserver side programming更新于 2025/3/14 11:24:17
在本文中,我们将学习如何使用 map 函数查找 1 数量最多的行。给定一个二维数组,数组元素为 0 和 1。所有行都已排序。我们必须找到 1 数量最多的行。这里我们使用 map ()。map 函数是用于函数式编程的 Python 内置函数中最简单的一个。这些工具将函数应用于序列和其他可迭代对象。
假设输入是以下数组 -
[[0, 1, 1, 1, 1],[0, 0, 1, 1, 1],[1, 1, 1, 1, 1],[0, 0, 0, 0, 1]]
输出显示 1 数量最多的行 -
2
查找 1 数量最多的行
在此示例中,我们将使用 map() 函数查找 1 数量最多的行 -
示例
def maximumFunc(n): max1 = list(map(sum,n)) print ("Row with maximum number of 1s = ",max1.index(max(max1))) # Driver program if __name__ == "__main__": n = [[0, 1, 0, 1, 1],[1, 0, 0, 0, 1],[1, 1, 1, 0, 1]] maximumFunc(n)
输出
Row with maximum number of 1s = 2
使用 for 循环查找具有最多 1 的行
在此示例中,我们将使用 for 循环简单地查找具有最多 1 的行 −
示例
m = [[0, 1, 0, 1, 1],[1, 0, 1, 0, 1],[1, 0, 1, 0, 1]] mrows = len(m) max1 = 0 for k in range(mrows): c = m[k].count(1) if(c >= max1): max1 = c res = k+1 print("The row with maximum number of 1s = ", res)
输出
The row with maximum number of 1s = 3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

