- Sample code:
def double(x):
return 2 * x
def square(x):
return x * x
def func(g, arr):
return [g(x) for x in arr]
def main():
arr1 = func(double, [1, 2, 3, 4])
arr2 = func(square, [1, 2, 3, 4])
print("arr1 =", arr1, ", arr2 =", arr2)
if __name__== "__main__" :
main()
- The output is as follows:
('arr1 =', [2, 4, 6, 8], ', arr2 =', [1, 4, 9, 16])
- Source code explanation:
In a given function func(g, arr)
, the expression is a form of List Comprehension. What it does is apply the function to each element in the list and store the result in a new list. [g(x) for x in arr]
g
arr
x
The process of explaining [g(x) for x in arr]
is as follows:
- For
arr
each element in the listx
, the following steps are performed in order:- Pass the element
x
to the functiong
for processing, ie callg(x)
. - Add the result of function
g
processing to a new list.
- Pass the element
- Finally returns a new list containing all processing results.
Summarize:
The effect of list comprehension and map is the same, for example, the following code:
arr3 = map(double , [1 , 2 , 3 , 4])
输出:arr3 =', [2, 4, 6, 8]
和上面的arr1的结果是一样的