Learn python · built-in functions (range(), zip(), sorted(), map(), reduce(), filter())

Posted by dcro2 on Thu, 30 Dec 2021 03:03:24 +0100

range function

It can generate a specified number sequence

Use case:

'''
range(start,stop,step)
Parameters:
    start : The starting value, the default value is 0
    stop  :  End value
    step:  Optional. The default step value is 1
 Return value: iteratable object, numeric sequence
'''
#How the range function is used
# Write only one parameter, that is, from zero to 10, 9
 res = range(11)

# When there are two parameters, the first parameter is the start value and the second parameter is the end value (before the end value)
 res = range(5,10)

# Three parameters, parameter 1 is the start value, parameter 2 is the end value, and parameter 3 is the step value
 res = range(1,10,3)

# Gets a flashback sequence of numbers
 res = range(10,0,-1)
 res = range(10,0,-2)

res = range(-10,-20,-1)
res = range(-20,-10)
res = range(-10,10)
print(list(res))

How to extract the sequence of numbers returned by the range() function:

# Method for obtaining the sequence of numbers returned by the range function
 res = range(10)
 1. Turn into list List data
 print(list(res))

# 2.  Traversal through the for loop
 for i in res:
     print(i)

# 3.  Convert to iterator and call with the next function
 res = iter(res)
 print(next(res))
 print(next(res))

zip() function

zip function can accept multiple iteratable objects, and then combine the ith element in each iteratable object to form a new iterator

Example:

'''
Parameters:*iterables,Any iteratable object
 Return value: an iterator that returns a tuple
'''
var1 = '1234'
var2 = ['a','b','c']
var3 = ('A','B','C','D')
# Call the zip function to form a new tuple iterator
res = zip(var1,var2,var3)
# print(res,type(res))

for i in res:
    print(i)
'''
('1', 'a', 'A')
('2', 'b', 'B')
('3', 'c', 'C')
('4', 'd', 'D')
'''


# zip() combined with the * operator can be used to disassemble a list:
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print(list(zipped))

print(zip(x, y)) # Iterator object,
print(*zip(x, y))# Combined multiple tuple data

Other built-in functions

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 function

# Mathematical correlation function

# Gets the absolute value of a number
 print(abs(-99.99))

# Summation starts from start, sums items in iterable from left to right, and returns the total value
 print(sum([1,2,3]))

# Get maximum
 print(max([1,2,3]))
 print(max(99,12,45))

# Get minimum value
 print(min([2,1,6,-9]))
 print(min(6,7,1,0,-2))

# The power operation returns the y-power of x
 print(pow(2,3))

# rounding
 r = round(3.1415926)
 r = round(3.1415926,2) # How many decimal places are reserved

 r = round(4.5) # Odd advance and even retreat 1.5 = 2, 2.5 = 2, 3.5 = 4, 4.5 = 4
 print(r)

Binary correlation function

# bin() converts the numeric type to binary
print(bin(123)) # 0b1111011

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

# oct() to octal 01234567
 print(oct(123)) # 0o173

# hex() to hex 0123456789abcdef
 print(hex(123)) # 0x7b
# Convert characters to ascii
r = ord('a')
print(r)

# Convert ascii to characters
r = chr(65)
print(r)

Higher order function

sorted(iterable,[reverse,key])

Take out the elements in the iteratable data one by one, put them into the key function for processing, sort them according to the return result in the function, and return a new list

'''
Function: sorting
 Parameters:
    iterable Iteratable data (container type data, range Data sequence, iterator)
    reverse  Optional. Whether to reverse. The default is False,No inversion, True reversal
    key      Optional, can be a custom function or a built-in function
 Return value: the sorted result
'''
arr = [3,7,1,-9,20,10]
# By default, it is sorted from small to large
 res = sorted(arr)  # [-9, 1, 3, 7, 10, 20]

# You can sort from large to small
 res = sorted(arr,reverse=True)  # [20, 10, 7, 3, 1, -9]

# Use the abs function (find the absolute value) as the key keyword parameter of sorted
res = sorted(arr,key=abs)
 print(res)

# Using custom functions
 def func(num):
     print(num,num % 2)
     return num % 2

 arr = [3,2,4,6,5,7,9]

 # Use custom functions in the sorted function to process data
 res = sorted(arr,key=func)
 print(res)

# Optimized version
arr = [3,2,4,6,5,7,9]
res = sorted(arr,key=lambda x:x%2)
print(res)

map(func, *iterables)

Each element in the passed in iteratable data is put into the function for processing, and a new iterator is returned

'''
Parameters:
    func Function custom function|Built in function
    iterables: Iteratable data
 Return value: iterator
'''

# (1) Convert a list of string numbers to an integer number list
# ['1','2','3','4']  # ==> [1,2,3,4]
# Common treatment methods
 varlist = ['1','2','3','4']  # ==> [1,2,3,4]
 newlist = []
 for i in varlist:
     newlist.append(int(i))
 print(newlist)

# Use the map function for processing
 varlist = ['1','2','3','4']
 res = map(int,varlist) # <map object at 0x104ea8890>
 print(list(res))

# (2) [1,2,3,4] ==> [1,4,9,16]

# Common method
 varlist = [1,2,3,4]
 newlist = []
 for i in varlist:
     res = i ** 2
     newlist.append(res)
 print(newlist)

# Use the map function to process this data
varlist = [1,2,3,4]
 def myfunc(x):
     return x ** 2
 res = map(myfunc,varlist)
 print(res,list(res))

# Optimized version
 res = map(lambda x:x**2,varlist)
 print(res,list(res))


# Practice Homework
# (3) ['a','b','c','d'] ==> [65,66,67,68]

reduce(func,iterable)

Each time, take out two elements from iterable and put them into func function for processing to get a calculation result. Then put the calculation result and the third element in iterable into func function to continue the operation. The obtained result and the subsequent fourth element are added into func function for processing, and so on until the last element participates in the operation

'''
Parameters:
    func:  Built in function or custom function
    iterable:  Iteratable data
 Return value: the final operation result
 Note: use reduce Function needs to be imported from functools import reduce
'''

from functools import reduce

# (1) [5,2,1,1] ==> 5211

# Common method
varlist = [5,2,1,1]
res = ''
for i in varlist:
    res += str(i)
res = int(res)
print(res,type(res))
'''
5 2 1 1
5 * 10 + 2 == 52
52 * 10 + 1 == 521
521 * 10 + 1 == 5211
'''

# Complete with reduce
def myfunc(x,y):
    return x*10+y
varlist = [5,2,1,1]
# Call function
res = reduce(myfunc,varlist)
print(res,type(res))

# (2) Put the string '456' = = > 456
#  How to solve the above problem when the int method cannot be used for type conversion

# Defines a function that returns an integer number given a string number
def myfunc(s):
    vardict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
    return vardict[s]

# 1. First use the map function to convert the numeric string into an integer number
iter1 = map(myfunc,'456')

# 2. The values in the number list are processed twice using lambda
iter2 = reduce(lambda x,y:x*10+y,iter1)
print(iter2)

filter(func,iterable)

Filter the data and take each element in iterable to func function for processing. If the function returns True, the data will be retained, and if it returns False, the data will be discarded

'''
Parameters:
    func  Custom function
    itereble:  Iteratable data
 Return value: an iterator composed of retained data
'''
# It is required to keep all even numbers and discard all odd numbers
varlist = [1,2,3,4,5,6,7,8,9]

# Common method implementation
 newlist = []
 for i in varlist:
     if i % 2 == 0:
         newlist.append(i)
 print(newlist)

# Processing with filter

 Define a function to judge whether the current function is even, and even returns True,Odd return False
 def myfunc(n):
     if n % 2 == 0:
         return True
     else:
         return False

 # Call the filter function for processing
 it = filter(myfunc,varlist)
 print(it,list(it))

# Optimized version
it = filter(lambda n:True if n % 2 == 0 else False,varlist)
print(it,list(it))

Topics: Python