Home Backend Development Python Tutorial Introduction to the use of Pythont special syntax filter, map, reduce, apply

Introduction to the use of Pythont special syntax filter, map, reduce, apply

Mar 07, 2017 pm 04:26 PM
apply filter map reduce

(1)lambda

lambda is a very useful syntax in Python, which allows you to quickly define a single-line minimal function. Similar to macros in C language, they can be used wherever a function is required.

The basic syntax is as follows:

Function name = lambda args1,args2,...,argsn : expression

For example:

add = lambda x,y : x + y
print add(1,2)
Copy after login

(2) filter

The filter function is equivalent to a filter. The function prototype is: filter(function, sequence), which means sequence sequence Each element in the sequence executes the function in turn. The function here is a bool function. For example:

sequence = [1,2,3,4,5,6,7,8,9,10]
fun = lambda x : x % 2 == 0
seq = filter(fun,sequence)
print seq
Copy after login

The following code means to filter out the elements in the sequence. All even numbers.

The filter function prototype is roughly as follows:

def filter(fun,seq):
    filter_seq = []
    for item in seq:
        if fun(item):
            filter_seq.append(item)
    return filter_seq
Copy after login

(3) map

The basic form of map is: map(function, sequence), which applies the function function to the sequence sequence and then returns a final result sequence. For example:

seq = [1,2,3,4,5,6]
fun = lambda x : x << 2

print map(fun,seq)
Copy after login

The function source code of map is roughly as follows:

def map(fun,seq):
    mapped_seq = []
    for item in seq:
        mapped_seq.append(fun(item))
    return mapped_seq
Copy after login

(4)reduce

The form of the reduce function is: reduce(function, sequence, initVal), function represents a binary function, sequence represents the sequence to be processed, and initVal represents processing initial value. For example:

seq = [1,2,3,4,5,6,7,8,9,10]
fun = lambda x,y: x + y

print reduce(fun,seq,0)
Copy after login

means accumulating each element in the sequence seq starting from the initial value 0, so the result is 55

## The source code of the #reduce function is roughly as follows:


def reduce(fun,seq,initVal = None):
    Lseq = list(seq)
    if initVal is None:
        res = Lseq.pop(0)
    else:
        res = initVal
    for item in Lseq:
        res = fun(seq,item)
    return res
Copy after login

(5) apply

apply is used To indirectly replace a function, such as:


def say(a,b):
    print a,b

apply(say,(234,&#39;Hello World!&#39;))
Copy after login
For more Pythont special syntax filter, map, reduce, apply usage instructions, please pay attention to the PHP Chinese website for related articles!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does springboot read lists, arrays, map collections and objects in yml files? How does springboot read lists, arrays, map collections and objects in yml files? May 11, 2023 am 10:46 AM

application.yml defines the list collection. The first way is to use the @ConfigurationProperties annotation to obtain all the values ​​​​of the list collection type:code:status:-200-300-400-500. Write the entity class corresponding to the configuration file. What needs to be noted here is that defining the list Collection, first define a configuration class Bean, and then use the annotation @ConfigurationProperties annotation to obtain the list collection value. Here we will explain the role of the relevant annotations. @Component hands over the entity class to Spring management @ConfigurationPropertie

How to set expiration time map in Java How to set expiration time map in Java May 04, 2023 am 10:13 AM

1. Technical background In actual project development, we often use caching middleware (such as redis, MemCache, etc.) to help us improve the availability and robustness of the system. But in many cases, if the project is relatively simple, there is no need to specifically introduce middleware such as Redis to increase the complexity of the system in order to use caching. So does Java itself have any useful lightweight caching components? The answer is of course yes, and there is more than one way. Common solutions include: ExpiringMap, LoadingCache and HashMap-based packaging. 2. Technical effects to realize common functions of cache, such as outdated deletion strategy, hotspot data warm-up 3. ExpiringMap3.

How to convert objects to Maps in Java - using BeanMap How to convert objects to Maps in Java - using BeanMap May 08, 2023 pm 03:49 PM

There are many ways to convert javabeans and maps, such as: 1. Convert beans to json through ObjectMapper, and then convert json to map. However, this method is complicated and inefficient. After testing, 10,000 beans were converted in a loop. , it takes 12 seconds! ! ! Not recommended. 2. Obtain the attributes and values ​​of the bean class through Java reflection, and then convert them into the key-value pairs corresponding to the map. This method is the second best, but it is a little more troublesome. 3. Through net.sf.cglib.beans.BeanMap Method in the class, this method is extremely efficient. The difference between it and the second method is that because of the use of cache, the bean needs to be initialized when it is first created.

What are the ways to implement thread safety for Map in Java? What are the ways to implement thread safety for Map in Java? Apr 19, 2023 pm 07:52 PM

Method 1. Use HashtableMapashtable=newHashtable(); This is the first thing everyone thinks of, so why is it thread-safe? Then take a look at its source code. We can see that our commonly used methods such as put, get, and containsKey are all synchronous, so it is thread-safe publicsynchronizedbooleancontainsKey(Objectkey){Entrytab[]=table;inthash=key.hashCode( );intindex=(hash&0x7FFFFFFF)%tab.leng

Optimize the performance of Go language map Optimize the performance of Go language map Mar 23, 2024 pm 12:06 PM

Optimizing the performance of Go language map In Go language, map is a very commonly used data structure, used to store a collection of key-value pairs. However, map performance may suffer when processing large amounts of data. In order to improve the performance of map, we can take some optimization measures to reduce the time complexity of map operations, thereby improving the execution efficiency of the program. 1. Pre-allocate map capacity. When creating a map, we can reduce the number of map expansions and improve program performance by pre-allocating capacity. Generally, we

How to configure and use the map module in Nginx server How to configure and use the map module in Nginx server May 21, 2023 pm 05:14 PM

The map directive uses the ngx_http_map_module module. By default, nginx loads this module unless artificially --without-http_map_module. The ngx_http_map_module module can create variables whose values ​​are associated with the values ​​of other variables. Allows classification or simultaneous mapping of multiple values ​​​​to multiple different values ​​​​and storage in a variable. The map directive is used to create a variable, but only performs the view mapping operation when the variable is accepted. For processing requests that do not reference variables, this The module has no performance shortcomings. 1.ngx_http_map_module module instruction description map syntax

Example analysis of Java Fluent Mybatis aggregation query and apply method process Example analysis of Java Fluent Mybatis aggregation query and apply method process May 22, 2023 pm 01:31 PM

Data preparation: In order to aggregate the conditions of the query, several pieces of data are added. MIN we try to get the minimum age. Method implementation @OverridepublicIntegergetAgeMin(){Mapresult=testFluentMybatisMapper.findOneMap(newTestFluentMybatisQuery().select.min.age("minAge").end()).orElse(null);returnresult!=null?Convert.toInt(result.get (&qu

How to solve the '[Vue warn]: Failed to resolve filter' error How to solve the '[Vue warn]: Failed to resolve filter' error Aug 19, 2023 pm 03:33 PM

Methods to solve the "[Vuewarn]:Failedtoresolvefilter" error During the development process using Vue, we sometimes encounter an error message: "[Vuewarn]:Failedtoresolvefilter". This error message usually occurs when we use an undefined filter in the template. This article explains how to resolve this error and gives corresponding code examples. When we are in Vue

See all articles