Detailed explanation of built-in functions and recursion in Python basics

PHP中文网
Release: 2017-06-21 13:18:41
Original
1678 people have browsed it

1. Built-in functions

The following are briefly introduced:

1.abs() Find the absolute value

2. all() If all elements of iterable are true (or if the iterable is empty), returns <span class="pre">True</span>

3.any () If any element of iterable is true, returns <span class="pre">True</span>. If iterable is empty, return <span class="pre">False</span>

4.callable() If the object parameter appears adjustable, return <span class="pre">True</span>, otherwise return <span class="pre">False</span>

##5.divmod() with two takes as arguments a (non-complex) number and returns a pair of numbers consisting of the quotient and remainder when using integer division. For mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a<span class="pre">//<span class="pre">b,<span class="pre">a<span class="pre">%<span class="pre">b)<span class="pre"></span></span></span></span></span></span> same. For floating point numbers, the result is (q,<span class="pre">a<span class="pre">%<span class="pre">b)<span class="pre"></span></span></span></span>, where q Usually math.floor(a<span class="pre">/<span class="pre">b)<span class="pre"></span></span></span>, but can be less than 1

6.enumerate() parameters must be iterable objects. The function results in an iterator, which outputs elements and corresponding index values.

7.eval() Extract and execute

8.frozenset() immutable collection, the collection defined by frozenset() cannot add or delete elements

9.globals() Returns a dictionary representing the current global symbol table. This is always a dictionary of the current module (inside a function or method, this is the module in which it is defined, not the module it is called from)

10.round() on the arguments Rounding

11.sorted() Sort without changing the original list

l=[1,2,4,9,-1]print(sorted(l)) #从小到大print(sorted(l,reverse=True)) #从大到小
Copy after login

12.zip() Zipper function

Create an iterator that aggregates elements from each iterator.

Returns an iterator of tuples, where the

i-th tuple contains the ith element from each argument sequence or iteration. The iterator stops when the shortest input iterable is exhausted. Taking a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator

13.max()

Returns the maximum item of the iterable or the largest of two or more arguments.

If a positional argument is provided, it should be an iterable. Returns the largest item in the iteration. If two or more positional arguments are supplied, the largest positional argument is returned.

max() can specify the key (that is, specify the part to be compared)

14.map() mapping

Returns an iterator, which applies

function Each item to iterable produces the result

l=[1,2,3,4]
m=map(lambda x:x**2,l)print(list(m))        ----->[1, 4, 9, 16]
Copy after login

15.reduce() merge

from functools import reduce

res=0for i in range(100):
    res+=iprint(res)
Copy after login
16.filter() filters and retains elements whose Boolean value is True

names=['alex_sb','yuanhao_sb','wupeiqi_sb','egon']print(list(filter(lambda name:name.endswith('_sb'),names)))--->['alex_sb', 'yuanhao_sb', 'wupeiqi_sb']
Copy after login
For detailed introduction of built-in functions, please refer to the following:

2. Anonymous Function (lambda expression)

def func(x):return x**2print(func(2))lambda x:x**2        #上边的函数就可以直接写成这种形式
Copy after login
lambda function has its own return value

Anonymous functions can only replace some very simple functions and are mainly used in conjunction with other functions

Another situation is that some functions are used only once after being defined. If they are not deleted, they will occupy memory space, and deletion will be very troublesome. In this case, anonymous functions can be used

3. Recursion

In the process of calling a function, the function itself is used directly or indirectly

The recursion efficiency is very low, and the current state needs to be retained when entering the next recursion. Python is not like other Language, there is no tail recursion, but Python has restrictions and does not allow users to recurse infinitely

Characteristics of recursion:

1. There must be a clear end condition

2 .Every time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion

3. Recursion efficiency is not high, and too many recursion levels will cause stack overflow

Example:

# 1 文件内容如下,标题为:姓名,性别,年纪,薪资#
# egon male 18 3000# alex male 38 30000# wupeiqi female 28 20000# yuanhao female 28 10000#
# 要求:# 从文件中取出每一条记录放入列表中,# 列表的每个元素都是{'name':'egon','sex':'male','age':18,'salary':3000}的形式#
# 2 根据1得到的列表,取出薪资最高的人的信息# 3 根据1到的列表,取出最年轻的人的信息# 4 根据1得到的列表,将每个人的信息中的名字映射成首字母大写的形式# 5 根据1得到的列表,过滤掉名字以a开头的人的信息# 6 使用递归打印斐波那契数列(前两个数的和得到第三个数)#     0 1 1 2 3 4 7...with open('b.txt',encoding='utf-8')as f:

l=[{'name': line.split()[0], 'sex': line.split()[1], 'age': line.split()[2], 'salary': line.split()[3]} \for line in f]#2.print(max(l,key=lambda i:i['salary']))#3.print(min(l,key=lambda i:i['age']))#4.m=map(lambda x:x['name'].capitalize(),l)print(list(m))#5.print(list(filter(lambda x:not(x['name'].startswith('a')),l)))#6.def f(n):if n==0:return 0elif n==1:return 1else:if n==1000:return f(1000)else:return f(n-2)+f(n-1)for i in range(150):print(f(i))
Copy after login

The above is the detailed content of Detailed explanation of built-in functions and recursion in Python basics. For more information, please follow other related articles on the PHP Chinese website!

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