Use of Python List Comprehension (List Comprehension)

  • 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] garrx

The process of explaining [g(x) for x in arr]is as follows:

  • For arreach element in the list x, the following steps are performed in order:
    • Pass the element xto the function gfor processing, ie call g(x).
    • Add the result of function gprocessing to a new list.
  • 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的结果是一样的

Guess you like

Origin blog.csdn.net/mldxs/article/details/131414749
Recommended