程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

4_ Python advanced_ Usage of map/filter/reduce

編輯:Python

Catalog

  • map
    • Be careful
  • Filter
    • Be careful
  • Reduce

map

map Will ⼀ Functions are mapped to ⼀ individual transport ⼊ list On all elements of .
amount to Batch input collect Batch output .
⼤ Most of the time , send ⽤ Anonymous functions (lambda) To match map.

# The most basic method 
inputs = [1, 2, 3, 4, 5, 6]
outputs = []
for i in inputs:
outputs.append(i ** 3)
print(outputs)

Simplify

# Now the way 
inputs = [1, 2, 3, 4, 5, 6]
outputs = list(map(lambda x: x ** 3, inputs))
print(outputs)

You can even enter a series of functions in batches .

# Batch input a series of functions 
def Func1(x):
return x * x
def Func2(x):
return x + x
FuncList = [Func1, Func2]
for i in range(5):
res = map(lambda x: x(i), FuncList)
print(list(res))

The output is A set of lists

[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]

Be careful

stay python2 in map Go straight back to list ;
stay python3 Back in iterator ;
For compatibility python3, need list transformation ⼀ Next ;

Filter

filter Filter the elements in the list
filter return ⼀ A list of all elements that meet the requirements
Meet the requirements : When the function maps to this element, the return value is True
filter Be similar to ⼀ individual for loop , But it is ⼀ individual Built in functions , And faster .

# filter Example 
inputs = range(-10, 10)
outputs = list(filter(lambda x: x < 0, inputs))
print("The numbers which are less than 0 are: {}".format(outputs))

The output is :

The numbers which are less than 0 are: [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]

Be careful

stay python2 in filter Go straight back to list ;
stay python3 Back in iterator ;
For compatibility python3, need list transformation ⼀ Next ;

Reduce

When need is right ⼀ A list Conduct ⼀ Some calculations and Return results when ,Reduce Will become very useful .
for example : Calculate the sum of the squares of a list of integers .

# reduce Example 
from functools import reduce
inputs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
outputs = reduce(lambda x, y: x + y, inputs)

The output is :

print(" And is :{}".format(outputs))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved