Home > Backend Development > Python Tutorial > Python special syntax

Python special syntax

高洛峰
Release: 2016-10-19 13:32:12
Original
1617 people have browsed it

Python has some built-in special functions, which are very python-specific. Can make the code more concise.

You can see the example:

1 filter(function, sequence):

str = ['a', 'b', 'c', 'd']

def fun1(s): return s if s ! = 'a' else None

ret = filter(fun1, str)

print ret

## ['b', 'c', 'd']

Execute function(item) on the items in sequence one by one , the items whose execution result is True are composed into a List/String/Tuple (depending on the type of sequence) and returned.

can be regarded as a filter function.

2 map(function, sequence)

str = ['a', 'b', 'c', 'd']

def fun2(s): return s + ".txt"

ret = map (fun2, str)

print ret

## ['a.txt', 'b.txt', 'c.txt', 'd.txt']

Execute function(item) on the items in sequence one by one ), see the execution results form a List and return:

map also supports multiple sequences, which requires the function to also support a corresponding number of parameter inputs:

def add(x, y): return x+y

print map( add, range(10), range(10))

##[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

3 reduce(function, sequence, starting_value): def add1(x,y): return x + y

print reduce(add1, range(1, 100))

print reduce(add1, range(1, 100), 20)

## 4950 (Note: 1 +2+...+99)

## 4970 (Note: 1+2+...+99+20)

Iteratively calls the function on the items in the sequence. If there is a starting_value, it can also be used as the initial value. Call, for example, can be used to sum a List:

4 lambda:

g = lambda s: s + ".fsh"

print g("haha")

print (lambda x: x * 2) ( 3)

## haha.fsh

## 6

This is an interesting syntax supported by Python, which allows you to quickly define a single-line minimal function, similar to macros in C language, these functions are called lambda.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template