Python iterators, (higher-order functions), built-in functions

catalogue

iterator

range

start,stop

step

Mathematical correlation function

Binary correlation

sorted

map

reduce

filter

iterator

#Iterators are objects that can remember where to access traversal as a way to access collection elements
#Access starts from the first element of the collection until all the elements in the lead collection are accessed
#But iterators can only traverse from front to back, one by one, not backward
#Objects that can be called by the next() function and return the next value continuously are called iterators

# First, the range() function returns an iteratable object. If you use the range function to traverse from left to right 0 ~ 9
for x in range(10):
    print(x)

# In addition to the range function, there are sets
ganyu = [1,2,3,4,5]
# Normally read the contents of a collection
for i in ganyu:
    print(i)

# So if there is a very large data, a number represents a person's information, then the data you see at one time is limited
# for i in range(1,1000000):
#     print(i)

# iter
# Function: you can turn the iteratable object into an iterator object
# Parameters: iteratable objects (such as str, list, tuple, dict, set, range...)
# Return value: iterator object
# Note: an iterator must be an iteratable object, but an iteratable object is not necessarily an iterator
# What are iteratable objects? (such as str, list, tuple, dict, set, range...)
# What is an iterator? What is the method of use?
# An iterator is an object that remembers the location of the traversal
# Define a list. For ganyu0, the internal parameter is an iteratable object
ganyu0=['ganyu1','ganyu2','ganyu3','ganyu4']
for x in ganyu0:
    print(x)
# As mentioned above, you can use the for loop to traverse the data

# You can turn iteratable objects into iterators as follows
ganyu=iter(ganyu0)# Call iter function to pass ganyu0 into
print(ganyu,type(ganyu))
# Output < list_ iterator object at 0x000001CC49A6ED00> <class 'list_ Iterator '>, list is the list, and then it becomes iterator

# The use method of iterator. Use the next() function to call the iterator object
a=next(ganyu)# ganyu is the iteration object just transformed into
print(a)# Result print ganyu1
# Process: first define a list, define it as an iteratable object, then convert it into an iterator with iter function, access it with next(), and return the result of the first access
# Visit once every time, that is, take one out of it. If you visit ganyu0 again at this time

# The use method of iterator. Use the list() function to call the iterator object
b=list(ganyu)# List converts the remaining data types into list types here. If you call list at this time, all functions in the iterator will be directly fetched
print(b)

# The use method of iterator. Use the for loop to call the iterator object
for i in ganyu:
    print(i)

Scheme of iterator value
1. Call next() to get the data once at a time until the data is obtained
2. list() uses the list function to directly fetch all functions in the iterator
3. For # use the for loop to traverse the data of the iterator
Iterator value characteristics: take out one less until all are taken, and then get it again, and an error will be reported

'''
Methods of detecting iterators and iteratable objects
'''
from collections.abc import Iterator,Iterable
varstr = '123456'
res = iter(varstr)

#The type function returns the current data type
# The isinstance function detects whether a data is of a specified type
e=isinstance(varstr,Iterable)# True is an iteratable object
f=isinstance(varstr,Iterator)# False is an iteratable object
g=isinstance(res,Iterator)#True iteratable object
print(e,f,g)
# An iterator must be an iteratable object, but an iteratable object is not necessarily an iterator

range

The range function creates a specified sequence of numbers

Note: the returned is an iterable, which is just like a list in many aspects, so the list will not be printed when printing

Function syntax: start,stop,[step]
		start: Start value
		stop: End value
		step: Optional, step size

start,stop

# If the range function only writes one parameter, it means that by default, it starts from zero to the first digit of 10, that is, 9. The result generated by range is converted into list printout
ganyu1 = range(10)
print(list(ganyu1))
# If it is negative, the output is empty
ganyu2 = range(-10)
print(list(ganyu2))
# From 5 to 9, the first parameter is the start value and the second parameter is the value before the end value
ganyu3 = range(5, 10)
print(list(ganyu3))

step

# step
ganyu4 = range(1, 10, 3)
print(list(ganyu4))
# Countdown in steps of 1
ganyu5=range(10,0,-1)
print(list(ganyu5))
# negative
ganyu6=range(-1,-5,-1)
print(list(ganyu6))

Mathematical correlation function

'''
Built in functions related to data type conversion
'''
# int() converts other types of data to integers
# Convert float() to float type
# bool() to Boolean
# Convert complex() to complex
# str() to string type
# List to list type
# Tuple to tuple type
# Convert dict to dictionary type
# Convert set to collection type
'''
Variable correlation function
'''
# id() gets the ID ID ID of the current data
# type() gets the type string of the current data
# print() print of data
# input() gets the input data
# isinstance() detects whether it is the specified data type
'''
Mathematical correlation built-in function
'''
# Gets the absolute value of a number
print(abs(-100))
# Sum
print(sum([1, 2, 3]))
# Maximum
print(max([1, 2, 3, 4, 5]))
print(max(1, 2, 3, 3, 4, 5))
# minimum value
print(min([1, 2, 3, 4, 5]))
print(min(1, 2, 3, 3, 4, 5))
# exponentiation 
print(pow(5,5))
# rounding
print(round(88/9))# Base advance and even retreat
# Keep two decimal places
print(round(88/9,2))

Binary correlation

# Binary correlation
# bin() converts the numeric type to binary
print(bin(123))

# int() converts binary to integer
print(int(0b1111011))

# oct() to octal
print(oct(123))

# hex() to hex
print(hex(123))

# ascii character conversion
'''
128 position
'''
# Character to ascii
print(ord('a'))
# Character to ascii
print(chr(97))

sorted

Sort all iteratable objects

Operation principle: take out the elements in the iteratable data in turn, put them into the key function for processing, sort them with the return result, and return a new list

'''
Function: sorting
 Syntax: sorted(iterable, cmp=None, key=None, reverse=False)
Parameters: iterable:Iteratable data (including container type data, range Data sequence, iterator)
	 key:Optional. Functions can be built-in functions or user-defined functions
     reverse:Optional. Whether to reverse. The default value is False
 Return value: sorted function
'''
# First define an unordered list
ganyu = [1, 2, 3, 4, -1, 0, -2]
# Using the sorted function
ganyu1 = sorted(ganyu)
print(ganyu1)  # Output [- 2, - 1, 0, 1, 2, 3, 4] is sorted from small to large by default

# From large to small [reverse]
ganyu2 = [1, 2, 3, 4, -1, 0, -2]
ganyu3 = sorted(ganyu2, reverse=True)
print(ganyu3)

# Key. abs is used as the key parameter of sorted
ganyu4 = sorted(ganyu2, key=abs)
print(ganyu4)  # Output [0, 1, - 1, 2, - 2, 3, 4]. During the running process, first process the unordered list and convert it into absolute value 1,2,3,4,1,0,2. After sorting, convert it back


# Using custom functions
ganyu5 = [1, 2, 3, 4, 5]
def num(aa):
    return aa % 10# Remainder 10 and sort
ganyu5 = sorted(ganyu5, key=num)
print(ganyu5)

# Optimize with lambda function
ganyu5 = [1, 2, 3, 4, 5]
ganyu5 = sorted(ganyu5, key=lambda x:x%10)
print(ganyu5)

map

Returns an iterator that applies function to each item in iterable and outputs its result

'''
Syntax: map(func, *iterables)
parameter    func: function ==>Custom function|Built in function
       *iterables: One or more iteratible data
 Return value: new iterator
 Function: put each element in the passed in iteratable data into the function for processing and return a new iterator
'''
# ['1', '2', '3', '4'] changed to [1, 2, 3, 4] format
# Method 1
ganyu = ['1', '2', '3', '4']
newlist = []
# Convert the string 1 to the number 1 and pass it into the newlist list
for i in ganyu:
    newlist.append(int(i))  # Use append to append the i converted to int to the newlist
print(newlist)

# Method 2
ganyu = ['1', '2', '3', '4']
res = map(int, ganyu)
print(res)  # <map object at 0x000002A41E8373D0>
print(list(res))

# Use the for in process to change [1,2,3,4] to [1,4,9,16]
ganyu1 = [1, 2, 3, 4]
newlist = []
for i in ganyu1:
    newlist.append(i * i)
print(newlist)

# Using map custom function processing
ganyu2 = [1, 2, 3, 4]
def ganyu3(x):
    return x**2
res = map(ganyu3, ganyu2)
print(res)
print(list(res))

# Optimize processing using lamdba function
ganyu2 = [1, 2, 3, 4]
print(list(map(lambda x:x**2, ganyu2)))

'''
'a','b','c','d'To 97,98,99,100
'''
ganyu2 = ['a','b','c','d']
res = map(lambda x:ord(x), ganyu2)
print(res)
print(list(res))

ganyu2 = ['a','b','c','d']
res = map(lambda x:ord(x.upper()), ganyu2)
print(res)
print(list(res))

reduce

Each time, take out two elements from the iterable and put them into the function function for calculation to obtain a processing result. Then put the calculation result and the third element in the iterable into the function function to continue the operation. The obtained result and the subsequent fourth element are added into the function function to continue the processing until all elements participate in the operation

# When reduce is used, due to Python 3 X reduce() has been moved to the functools module. If you want to use it, you need to introduce the functools module to call the reduce() function

from functools import reduce

'''
reduce()
Syntax: reduce(function, sequence[, initial])
            function: Built in function|Custom function
            iterable: Iteratable object
 Return value: final calculation result
 Function: every time from iterable Take out two elements and put them into function Function, get a processing result, and then compare the calculation result with iterable The third element in, put into function Function, the result and the fourth element after it are added to function Function until all elements participate in the operation

'''
# Stack the numbers in the list into ten thousand digits
# [1,2,3,4]==>1234
# Common method
ganyu = [1, 2, 3, 4]
ganyu1 = ""
for i in ganyu:
    ganyu1 += str(i)  # i is each number in ganyu, str converts i into a string, and then splices each string
    ganyu2 = int(ganyu1)
print(ganyu2, type(ganyu2))


# reduce method
# Define function
def ganyu3(x, y):
    return x * 10 + y
res = reduce(ganyu3, [1, 2, 3, 4])
print(res)
# Process: first, a list is defined. Each time, the reduce function takes out two elements from the iterable, puts them into the function function for calculation, and obtains a processing result, that is, bring 1 and 2 into the user-defined function ganyu3, return the value * 10+y, and so on

filter

It is used to filter the sequence, filter out the unqualified elements, and return a new list composed of qualified elements

'''
Syntax: filter(function,iterable)
			function: Built in function|Custom function
            iterable: Iteratable object
 Function: filter data and put the current iterable Every element in the function If the function returns True,Keep, otherwise discard
'''

# Keep all even numbers
# Method 1
def ganyu(x):
    if x % 2 == 0:
        return x
ganyu1 = filter(ganyu, [1, 2, 3, 4, 5, 6])
print(list(ganyu1))

# Method 2
ganyu2 = [1, 2, 3, 4, 5, 6]
newlist = []
for i in ganyu2:
    if i % 2 == 0:
        newlist.append(i)
print(newlist)

# Method 3
ganyu3=filter(lambda a:True if a % 2 ==0 else False,[1,2,3,4,5,6])
print(list(ganyu3))

Keywords: Python Back-end function

Added by greeneel on Sun, 30 Jan 2022 07:38:34 +0200