Examples of common usage of Python built in efficiency functions

  • 2020-11-26 18:50:31
  • OfStack

This article illustrates the common use of built-in efficiency functions in Python. To share for your reference, the details are as follows:

1. filter(function,sequence)

Each element in sequence is filtered into the function function (you can customize it and return True or False), and the eligible elements are returned and reorganized into 1 String,List,Tuple, etc. (same as sequence1).

The sample


def func(x):
  return x%2==0 and x%3==0
filter(func,(3,6,8,12,15,21))
#(6, 12)

2. map(functiom,sequence)

Each element in sequence, in turn, is passed to the function function (which can be customized and returns a numeric value) to calculate that whatever type sequence is, it returns List

The sample


def func(x):
  return x*2
map(func,(3,6,8,12,15,21))
#[6, 12, 16, 24, 30, 42]

map supports multiple sequence inputs, but function also needs to have the same number of parameters


def func(x,y):
  return x+y
seq1=[3,6,4,8]
seq2=[6,4,3,7]
map(func,seq1,seq2)
#[9, 10, 7, 15]

Note: The above example is in python2.7. python3 should be used as follows


>>> map_obj = map(lambda x:x+1,[1,2,3,4])
>>> map_obj
<map object at 0x0000014C511BD898>
>>> list(map_obj)
[2, 3, 4, 5]

3. reduce(function, sequence, starting_value)

The sequential iteration of item in sequence calls function, for example, which can be used to sum List:


def add(x,y):
  return x+y
reduce(add,[3,6,4,8])
#21
# Equivalent to running ' 3+6+4+8'=21

If starting_value is present, it can also be called as an initial value


def subtract(x,y):
  return x-y
reduce(subtract,[3,6,4],20)
#7
# The equivalent of '20-3-6-4'=7

lambda anonymous function

Grammar: lambda 参数1,参数2(,参数n..):表达式 Returns 1 function object

The sample


func=lambda x,y:x+y
func(3,5)
#8

Combine lambda and reduce


reduce(lambda x,y:x+y,[3,6,4,8])
#21

For more information about Python, please refer to the following topics: Summary of Python Function Skills, Summary of Python Mathematical Operation Skills, Python Data Structure and Algorithm Tutorial, Python String Operation Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: