(final review) Python built-in functions

Posted by shya on Thu, 25 Nov 2021 22:52:11 +0100

(final review) Python built-in functions

(1) iter method:
The iter(object, sentinel) function is used to generate iterators
parameter
Object – a collection object that supports iteration.
sentinel – if the second parameter is passed, the parameter object must be a callable object (for example, a function). At this time, iter creates an iterator object, which is called every time__ next__ () method, object will be called.

it=iter(range(1,10))
print(next(it))
print(next(it))
print(next(it))
print(type(it))
print(list(it)) # This is the feature of the iterator: it can only traverse once, and discontinuous traversal will continue to traverse at the last end point until the end of a complete traversal
print(next(it)) # Because all the data in the it iterator has been traversed, the system will report an error
# Traceback (most recent call last):
#   File "D: \ software courseware \ exercise \ built-in function. Py", line 13, in < module >
#     print(next(it)) # Because all the data in the it iterator has been traversed, the system will report an error
# StopIteration
# 1
# 2
# 3
# <class 'range_iterator'>
# [4, 5, 6, 7, 8, 9]

(2) enumerate function:
For ordered collections, sometimes you need to retrieve the index of elements. You can use python's built-in enumerate function.
The enumerate function can turn a * * (iteratable object) * * into an index element pair, so that the index and the element itself can be iterated simultaneously in the for loop.

list_one = ['a','b','c']
for i in enumerate(list_one,start=1): # start indicates the initial value of the subscript, starting from 0 by default
    print(i)
    print(type(i)) # The type is tuple
    print(i[0]) # Print subscript 0 1 2 of list
print(type(enumerate(list_one)))  # In Python 3.x, to reduce memory, enumerate() returns an object.
print(list(enumerate(list_one)))
print(dict(enumerate(list_one)))
# (1, 'a')
# <class 'tuple'>
# 1
# (2, 'b')
# <class 'tuple'>
# 2
# (3, 'c')
# <class 'tuple'>
# 3
# <class 'enumerate'>
# [(0, 'a'), (1, 'b'), (2, 'c')]
# {0: 'a', 1: 'b', 2: 'c'}

(3) Zip (iteratable object 1, iteratable object 2, iteratable object 3...) function:
The zip() function is used to take the iteratable object as a parameter and package the corresponding elements in the object into tuples.
If the number of elements of each iteration object is inconsistent, the length of the returned list is the same as that of the shortest object. The tuple can be decompressed into a list by using the * operator.
The zip method is different in Python 2 and python 3: in Python 3.x, in order to reduce memory, zip() returns an object (iterator).

pack:

a=[1,2,4]
b=['a','b','c','d']
c=['x','y','n']
zipp =zip(a,b,)
print(type(zipp)) # In Python 3.x, to reduce memory, zip() returns an object.
print(zipp)
for i in zipp:
    print(i)
    print(type(i))
print(list(zipp)) # The zip method can return an iterator, so the output is an empty list
from collections import Iterator, Iterable, Generator
print(isinstance(zipp,Iterator))  # Check whether it is an iterator True
print(isinstance(zipp,Iterable))  # Check whether it is an iterative object True
print(isinstance(zipp,Generator)) # Check whether the generator is False
# <class 'zip'>
# <zip object at 0x0000028F4AA60880>
# (1, 'a')
# <class 'tuple'>
# (2, 'b')
# <class 'tuple'>
# (4, 'c')
# <class 'tuple'>
# []
# True
# True
# False

Unpacking:

ip=zip(*zipp)
print(type(ip))
print(zip(*zipp))
print(list(ip))
# <class 'zip'>
# <class 'zip'>
# <zip object at 0x00000214FD964DC0>
# [(1, 2, 4), ('a', 'b', 'c')]

(4) range(start, stop, step) function:
Parameter Description:
Start: count starts from start. The default is to start from 0.
Stop: count to the end of stop, but do not include stop.
Step: step size; the default value is 1.

print(tuple(range(5)))
print(list(range(1,5)))
print(set(range(0,6,2)))
# (0, 1, 2, 3, 4)
# [1, 2, 3, 4]
# {0, 2, 4}

(5) The sorted() function sorts all iteratable objects.

The difference between sort and sorted: sort is a method applied to a list. Sorted can sort all iteratable objects. List
The sort method returns an operation on an existing list without a return value, while the built-in function sorted returns a new list
list instead of the operation based on the original.

sorted(iterable, cmp=None, key=None, reverse=False)
Parameter Description:
Iteratable – iteratable object.
cmp - the function of comparison. This function has two parameters. The values of the parameters are taken from the iteratable object. The rules that this function must follow are: if it is greater than, it returns 1, if it is less than, it returns - 1, and if it is equal to, it returns 0.
key – it is mainly used to compare elements. There is only one parameter. The parameters of the specific function are taken from the iteratable object. Specify an element in the iteratable object to sort.
Reverse – collation, reverse = True descending, reverse = False ascending (default).

students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
print(sorted(students,key=lambda s:s[2])) # key specifies that the sorting rule is to compare the size of elements with subscript 2 in each element of students in ascending order
print(sorted(students, key=lambda s: s[2], reverse=True) ) # Descending order
# [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
# [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

(6)eval() function:
The eval() function is used to execute a * * (string) * * expression and return the value of the expression

x=6
print(eval( '3 * x' ))
print(eval('pow(2,2)'))
# 18
# 4

(7)map() function
The map() function maps the specified sequence according to the passed in function.
The map() function takes two parameters, one is the function function, and the other parameter is one or more sequences.
The map() function applies the incoming function to each element of the incoming sequence in turn, and returns the result as a new sequence.
The map() function is defined as:
map(function, sequence, sequence, ...) -> list
For example, we want to square each numeric element in a list sequence:

r = map(lambda x: x ** 2, [1, 2, 3, 4,]) # lambda declares an anonymous function
print(r)
print(list(r))
print("*"*20)
# [1, 4, 9, 16]

When there are multiple sequences in the second parameter of the map() function, the elements at the same position in each sequence will be used as parameters in turn, and the function function will be called.
For example, to sum the elements in the two sequences passed in by the map() function in turn, the program code is as follows:

def San(x,y): # Define a function
    return x+y
r1=map(San,[1, 2, 3, 4, 5], [6, 7, 8, 9, 10,11]) # Call the San function to map the sequence
print(list(r1))

When there are multiple sequences passed in by the map() function, we should pay attention to the number of parameters of the function, which should match the number of sequences passed in by the map() function.

r = map(lambda x, y: x + y, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10,11])
print(list(r))
# [7, 9, 11, 13, 15]

(8)reduce() function
The reduce() function applies the incoming function to a sequence [x1, x2, x3,...], and the function must receive two parameters.
The reduce () function continues to accumulate the result of the first calculation with the next element in the sequence. The reduce() function is defined as:

reduce(function, sequence, initial) -> value
The function parameter is a function with two parameters. The reduce() function takes elements from the sequence in turn, takes parameters with the result of the last call to the function function, and then calls the function function again.
For example:

from functools import reduce
r = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5],6) # The order of calculation is: ((1 + 6) + 2) + 3) + 4) + 5
print(r)
# 21

Find the factorial of a number:

m=reduce(lambda x,y:x*y ,range(1,6),6)
print(m)
# 720

Topics: Python html