Basic Python learning: Common built-in functions, basic python Functions
Preface
Python provides many built-in functions for various types. These built-in functions are used to perform similar operations on multiple types of objects, that is to say, the common operations of multiple types of objects are not mentioned 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. map applies the input function to each element of the iterated object in sequence, return the result as an Iterator.
For example, there is a functionf(x)=x^2
To apply this function tolist[1,2,3,4,5,6,7,8,9]
On:
A simple loop can be used to 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)
Use high-order functionsmap()
:
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])>>> list(r)[1, 4, 9, 16, 25, 36, 49, 64, 81]
Result r is an iterator and an iterator is an inert sequence.list()
The function calculates the entire sequence and returns a list.
If you want to convert all the numbers in this list into strings, usemap()
It's easy:
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))['1', '2', '3', '4', '5', '6', '7', '8', '9']
Exercises:Exploitationmap()
Function, which converts invalid English names entered by the user into upper-case letters and other lower-case standard names. 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()
A function also accepts two parameters. One is a function and the other is an iteratable object. reduce calculates the result of the Input Function Applied to each element of the iteratable object. Then return the final result.
The effect is:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
For example[1,2,3,4,5]
To an integer of 12345:
>>> from functools import reduce>>> def fn(x, y):... return x * 10 + y...>>> reduce(fn, [1, 2, 3, 4, 5])12345
Small exercise: Writeprod()
Function, which can accept a list and use reduce to calculate the product:
from functools import reducedef pro (x,y): return x * y def prod(L): return reduce(pro,L) print(prod([1,3,5,7]))
map()
Andreduce()
Comprehensive Exercise: Compile the str2float function to convert the string '192. 100' to floating point 123.
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) # The third parameter 0 is the initial value, corresponding to f in to_float
Filter ()
filter()
The function is used to filter sequences,filter()
It also accepts a function and a sequence,filter()
Apply the input function to each element in sequence, and decide whether to retain or discard the element based on whether the returned value is True or False.
For example, delete the even number in the list:
Def is_odd (n): return n % 2 = 1 list (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # result: [1, 5, 9, 15]
Exercise: Use filter () to calculate the prime number
One Method for Calculating prime numbers is the escret method, which is easy 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 screen out the multiples of 2 of the sequence:
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ,...
Take the first number 3 of the new sequence, it must be a prime number, and then use 3 to screen out the multiple of the sequence 3:
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 screen out the multiples of 5:
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ,...
Continue to screen to obtain all prime numbers.
Using Python to implement this algorithm, we first construct a series of numbers starting from 3:
Def _ odd_iter (): n = 1 while True: n = n + 2 yield n # This is a generator and a wireless Sequence
Define a filter function:
def _not_divisible(n): return lambda x: x % n > 0
Define a generator to continuously return the next Prime Number:
Def primes (): yield 2 it = _ odd_iter () # initial sequence while True: n = next (it) # The first number of returned sequences yield n it = filter (_ not_divisible (n), it) # construct a new sequence
Print the prime number within 100:
for n in primes(): if n < 100: print(n) else: break
Sorted ()
Python built-insorted()
The function can sort the list:
>>> sorted([36, 5, -12, 9, -21])[-21, -12, 5, 9, 36]
sorted()
A function is also a high-order function. You can also use a key function to perform custom sorting:
>>> sorted([36, 5, -12, 9, -21], key=abs)[5, 9, -12, -21, 36]
The function specified by the key acts on each element of the list and sorts the result returned by the key function.
By default, strings are sorted by ASCII size. Because 'Z' <'A', the result is that uppercase letters Z are placed before lowercase letters. If you want to ignore the case, convert them to lowercase for comparison:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)['about', 'bob', 'Credit', 'Zoo']
To perform reverse sorting, you do not need to change the key function. You can input the third parameter.reverse=True
:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)['Zoo', 'Credit', 'bob', 'about']
Exercises:Suppose we use a group of tuple to indicate the Student name and score:L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
. Usesorted()
Sort the above list by c score from high to low:
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)
Using anonymous functions is simpler:
L2=sorted(L,key=lambda t:t[1])print(L2)
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.