在Python中使用 map()函数求和二维数组
给定一个二维矩阵,我们需要找到矩阵中所有元素的总和?
例子:
Input : arr = [[1, 2, 3],
[4, 5, 6],
[2, 1, 2]]
Output : Sum = 26
这个问题可以通过迭代整个矩阵使用两个 for 循环轻松解决,但我们可以在Python中使用 map()函数快速解决这个问题。
# Function to calculate sum of all elements in matrix
# sum(arr) is a python inbuilt function which calculates
# sum of each element in a iterable ( array, list etc ).
# map(sum,arr) applies a given function to each item of
# an iterable and returns a list of the results.
def findSum(arr):
# inner map function applies inbuilt function
# sum on each row of matrix arr and returns
# list of sum of elements of each row
return sum(map(sum,arr))
# Driver function
if __name__ == "__main__":
arr = [[1, 2, 3], [4, 5, 6], [2, 1, 2]]
print ("Sum = ",findSum(arr))
输出:
26
map() 有什么作用?
map()函数将给定函数应用于可迭代(列表、元组等)的每个项目并返回结果列表。例如,请参见下面给出的示例:
# Python code to demonstrate working of map()
# Function to calculate square of any number
def calculateSquare(n):
return n*n
# numbers is a list of elements
numbers = [1, 2, 3, 4]
# Here map function is mapping calculateSquare
# function to each element of numbers list.
# It is similar to pass each element of numbers
# list one by one into calculateSquare function
# and store result in another list
result = map(calculateSquare, numbers)
# resultant output will be [1,4,9,16]
print (result)
输出 :
[1, 4, 9, 16]