Home >Backend Development >Python Tutorial >Introduction to Python's common built-in functions
The so-called built-in functions can be used directly without import. The following article mainly introduces some common built-in functions for basic learning of Python. The article introduces them to you in great detail through sample codes. Friends who need them can refer to them. Let's follow the editor to learn together.
Preface
Python provides many built-in functions to handle many types. The function of these built-in functions is that they can often Perform similar operations on multiple types of objects, that is, operations common to multiple types of objects. I won’t go into more details below. Let’s take a look at the detailed introduction.
map()
The map() function accepts two parameters, one is a function and the other is an iterable object (Iterable), map Apply the passed function to each element of the iterable object in turn, and return the result as an iterator.
For example, there is a function f(x)=x^2
, and you want to apply this function to a list[1,2,3,4, 5,6,7,8,9]
上:
Using a simple loop can achieve:
>>> def f(x): ... return x * x ... L = [] for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: L.append(f(n)) print(L)
Using advanced Function map()
:
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> list(r) [1, 4, 9, 16, 25, 36, 49, 64, 81]
The result r is an iterator, and the iterator is a lazy sequence, passed list()
The function lets it calculate the entire sequence and return a list.
If you want to convert all the numbers in this list into strings, use map()
. It’s simple:
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) ['1', '2', '3', '4', '5', '6', '7', '8', '9']
Small exercise: Use the map()
function to change the non-standard English name entered by the user into a standard name with the first letter capitalized and other lowercase letters. Input['adam', 'LISA', 'barT'],
Output['Adam', 'Lisa', 'Bart']
def normalize(name): return name.capitalize() l1=["adam","LISA","barT"] l2=list(map(normalize,l1)) print(l2)
reduce()
reduce()
The function also accepts two parameters, one is a function and the other is Iterable object, reduce will perform cumulative calculation on the result of applying the passed function to each element of the iterable object. Then return the final result.
The effect is: reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
For example, convert the sequence [1,2,3,4,5]
into an integer 12345:
>>> from functools import reduce >>> def fn(x, y): ... return x * 10 + y ... >>> reduce(fn, [1, 2, 3, 4, 5]) 12345
Small exercise: Write a prod()
function that can accept a list and use reduce to calculate the product:
from functools import reduce def pro (x,y): return x * y def prod(L): return reduce(pro,L) print(prod([1,3,5,7]))
map()
andreduce()
Comprehensive exercise: Write the str2float function to convert the string '123.456' into a floating point type 123.456
CHAR_TO_FLOAT = { '0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9, '.': -1 } def str2float(s): nums = map(lambda ch:CHAR_TO_FLOAT[ch],s) point = 0 def to_float(f,n): nonlocal point if n==-1: point =1 return f if point ==0: return f*10+n else: point =point *10 return f + n/point return reduce(to_float,nums,0)#第三个参数0是初始值,对应to_float中f
filter()
filter()
The function is used to filter the sequence, filter()
also accepts a function and a sequence, filter()
Apply the passed function to each element in turn, and then decide whether to keep or discard the element based on whether the return value is True or False.
For example, delete even numbers in the list:
def is_odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # 结果: [1, 5, 9, 15]
Small exercise: Use filter() to find prime numbers
One method of calculating prime numbers is the Ehrlich sieve method. Its algorithm is very simple to understand:
First, list all natural numbers starting from 2 and construct a sequence:
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
Take the first number 2 of the sequence, which must be a prime number, and then use 2 to filter out the multiples of 2 in the sequence:
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
Get the first number 3 of the new sequence, It must be a prime number, and then use 3 to filter out the multiples of 3 in the sequence:
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
Take the first number 5 of the new sequence, and then use 5 to filter out the multiples of 5 in the sequence:
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
Keep sifting and you can get all Prime number.
Use Python to implement this algorithm. First construct a period sequence starting from 3:
def _odd_iter(): n = 1 while True: n = n + 2 yield n #这是一个生成器,并且是一个无线序列
Define a filtering function:
def _not_pisible(n): return lambda x: x % n > 0
Define a generator to continuously return the next prime number:
def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_pisible(n), it) # 构造新序列
Print prime numbers within 100:
for n in primes(): if n < 100: print(n) else: break
sorted()
Python’s built-in sorted()
function can sort the list Sort:
>>> sorted([36, 5, -12, 9, -21]) [-21, -12, 5, 9, 36]
sorted()
The function is also a higher-order function and can also accept a key function to implement custom sorting:
>>> sorted([36, 5, -12, 9, -21], key=abs) [5, 9, -12, -21, 36]
The function specified by key will act on each element of the list and be sorted according to the result returned by the key function.
默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。如果想忽略大小写可都转换成小写来比较:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower) ['about', 'bob', 'Credit', 'Zoo']
要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True
:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) ['Zoo', 'Credit', 'bob', 'about']
小练习:假设我们用一组tuple表示学生名字和成绩:L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
。用sorted()
对上述列表分别按c成绩从高到低排序:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_score(t): for i in t: return t[1] L2=sorted(L,key= by_score) print(L2)
运用匿名函数更简洁:
L2=sorted(L,key=lambda t:t[1]) print(L2)
The above is the detailed content of Introduction to Python's common built-in functions. For more information, please follow other related articles on the PHP Chinese website!