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

Python Advanced Series (II)

編輯:Python

Catalog

Map,Filter and Reduce

Map

Filter

Reduce

set( aggregate ) data structure

intersection

Difference set


Map,Filter and Reduce

Map,Filter and Reduce Three functions can facilitate functional programming . We will discuss and understand them one by one through examples .

Map

Map A function is mapped to all elements of an output list . This is its specification :

map(function_to_apply, list_of_inputs)

Most of the time , We need to pass all the elements in the list to a function one by one , And collect the output . For example :

items = [1, 2, 3, 4, 5]
squared = []
for i in items:
    squared.append(i**2)

Map It can be achieved in a much simpler and more beautiful way . this is it :

items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

Most of the time , We use anonymous functions (lambdas) To match map, So I did the same thing above . Not only for the input of a list . We can even use a list of functions !

def multiply(x):
    return (x*x)
def add(x):
    return (x+x)
funcs = [multiply, add]
for i in range(5):
    value = map(lambda x: x(i), funcs)
    print(list(value))
    # translator's note : above print when , added list transformation , In order to python2/3 The compatibility of
    # stay python2 in map Go directly back to the list , But in python3 Return iterator
    # So in order to be compatible with python3, need list Change my 

Filter

seeing the name of a thing one thinks of its function ,filter Filter the elements in the list , And return a list of all the elements that meet the requirements , If the function is mapped to the element, the return value is True. Here is a short example :

number_list = range(-5, 5)
less_than_zero = filter(lambda x: x < 0, number_list)
print(list(less_than_zero))
# translator's note : above print when , added list transformation , In order to python2/3 The compatibility of
# stay python2 in filter Go directly back to the list , But in python3 Return iterator
# So in order to be compatible with python3, need list Change my
# Output: [-5, -4, -3, -2, -1]

This filter Similar to a for loop , But it is a built-in function , And faster .

Be careful : If map and filter If it doesn't look elegant to you , So you can look at another chapter : list / Dictionaries / Tuple derivation .

translator's note : In most cases, the derivation is more readable

Reduce

When you need to do some calculations on a list and return results ,Reduce It's a very useful function . for instance , When you need to calculate the product of a list of integers .

Usually in python You may use basic for Loop to complete the task .

Now let's try reduce:

from functools import reduce
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )

set( aggregate ) data structure

set( aggregate ) Is a very useful data structure . It is associated with the list (list) The behavior of is similar to , The difference lies in set Cannot contain duplicate values .

This is very useful in many cases . For example, you might want to check whether the list contains duplicate elements , You have two choices , The first one needs to use for loop , Just like this. :

some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = []
for value in some_list:
    if some_list.count(value) > 1:
        if value not in duplicates:
            duplicates.append(value)
print(duplicates)
### Output : ['b', 'n']

But there is a simpler and more elegant solution , That's using sets (sets), You just do it :

some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = set([x for x in some_list if some_list.count(x) > 1])
print(duplicates)
### Output : set(['b', 'n'])

Collections have some other methods , Let's introduce some of them .

intersection

You can be right ⽐ The intersection of two sets ( Data in both sets ), as follows :

valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.intersection(valid))
### Output : set(['red'])

Difference set

You can use difference sets (difference) Find valid data , It is equivalent to subtracting the data of another set from one set , example

Such as :

valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.difference(valid))
### Output : set(['brown'])

You can also use symbols to create collections , Such as :

a_set = {'red', 'blue', 'green'}
print(type(a_set))
### Output : <type 'set'>

Collections have some other methods , I would suggest that you visit the official documents and do a quick reading .


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