Higher order functions and file operations

Keywords: Python Pycharm

Higher order function

Taking functions as parameters, such functions are called high-order functions. High-order functions are the embodiment of functional programming, which refers to this highly abstract programming paradigm
Functional programming uses a lot of functions to reduce the repetition of code, so the program is relatively short and the development speed is fast.

  • Learn to use a function, mainly 3 points
    • Function name
    • Function has several parameters. What does each parameter mean
    • The return value of a function is mainly to know what the return value type is
  1. map()
    map(func,lst), apply the passed in function variable func to each element of the st variable, and form the result into a new list (Python 2) / D iterator (Python 3)
    map function:
  • Function name: map
  • Two parameters
    • Parameter 1: a function
    • Parameter 2: it is a sequence that can be traversed, such as list, set, dictionary, etc
  • Return value: map object, which is a reference to a new object
  • The map function executes the f1 function multiple times (times = number of elements in list l1)
  • Each time the f1 function is executed, the formal parameter x is sequentially assigned to the elements in the l1 list
  • The return value of f1 function will be put into a new sequence by map function
  • The new list has the same number of elements as the original list: why?
    If there are several elements in the original list, the f1 function will execute several times
    If the f1 function is executed several times, several data will be return ed
    The returned data is added to the new list, so it is consistent
  • The map function is very extensible: you can use set, list and tuper functions to convert the return value to the data type you want
l1 = [10, 20, 4, 5, 60]


def f1(x):
    return x * 2
    # return x
    # return 'b'
    # print(x)


# res = map(f1, l1)
res = map(lambda x: x * 2, l1)
print(res)
# new_list = list(res)
# new_list = tuple(res)
new_list = set(res)
print(new_list)

print('--------------------------')

"""
Case 2: will l2 Convert lowercase letters to uppercase letters in the list
"""
l2 = ['a', 'b', 'c', 'd']


def convert_upper(x):
    return x.upper()


# res = map(convert_upper, l2)
res = map(lambda x:x.upper(), l2)
print(list(res))

"""
3,Convert uppercase to lowercase in the list; Convert lowercase to uppercase
"""
l3 = ['a', 'B', 'C', 'd']


def convert(i):
    if i.isupper() is True:
        return i.lower()
    elif i.islower() is True:
        return i.upper()


res = map(convert, l3)
print(list(res))

  1. reduce()
    reduce(func, lst), where func must have two parameters. The result of each func calculation continues to accumulate with the next element of the sequence.
    Note: the parameter func passed in by reduce() must receive 2 parameters.
import functools

list1 = [1, 2, 3, 4, 5]


def my_sum(a, b):
    print(a, b)
    # return a + b
    return a * b


res = functools.reduce(my_sum, list1)
print(res)

  1. filter()
    The filter(func, lst) function is used to filter the sequence, filter out unqualified elements, and return a filter object. If you want to convert to a list, you can use list() to convert.
    If you want to filter out some qualified elements in the list, use the filter method
Put all numbers greater than 10 in the list into a new list
l1 = [10, 20, 4, 5, 60]


#
# def filter10(x):
#     if x > 10:
#         return x
#     else:
#         return ''
#
#
# res = map(filter10, l1)
# print(list(res))


def filter10(x):
    if x > 10:
        return x


# res = filter(filter10, l1)
res = filter(lambda x: x if x > 10 else '', l1)
print(list(res))

Common API for file content operation

Introduction to file operation

The function of file operation is to store some content (data) so that the next execution of the program can be used directly without having to make a new copy, saving time and effort

  • Basic steps of file operation
    These steps are the same whether you operate the file manually or through code
  • Open file
  • Read and write operations
  • Close file
    Note: you can only open and close files without any read-write operations

open

In Python, using the open function, you can open an existing file or create a new file

open(name,mode)

Name: is the name and string of the target file to be opened (can include the specific path where the file is located)
Mode: set the mode of opening files (access mode): read-only, write, append, etc.

  1. Open file mode
patterndescribe
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rbOpen a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
wOpen a file for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wbOpen a file in binary format for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
w+Open a file for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+Open a file in binary format for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
aOpen a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
abOpen a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file is opened in append mode. If the file does not exist, create a new file for reading and writing.
ab+Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.
  1. Quick experience
f=open('text.txt','w')

Note: f in this case is the file object of the open function

File object method

  1. write
  • grammar
object.write('content')
  • experience
# 1. Open the file 
f = open('test.txt', 'w') 
# 2. File writing 
f.write('hello world') 
# 3. Close the file 
f.close()

be careful:
1. W and a modes: if the file does not exist, the file is created; If the file exists, the w mode is cleared before writing, and the a mode is appended directly to the end
2. r mode: if the file does not exist, an error is reported

  1. read
  • read()
File object.read(num)

Num indicates the length of the data to be read from the file (in bytes). If num is not passed in, it means that all the data in the file is read.

  • readlines()
    readlines can read the contents of the whole file at one time in the form of lines, and return a list, in which the data of each line is an element.
f = open('test.txt') 
content = f.readlines() 
# ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc'] 
print(content) 
# Close file 
f.close()
  • read and readlines

    • The read and readLines methods read all the file contents by default. The difference is
    • When the raed method returns a string, the readLine method returns a list, taking each line of the file as an element of the list
    • The read method can read binary files, while the readLines method mainly reads text files
res = open('aa.txt', 'r')
content = res.read()  # Read all by default
print(content)
# Close file
res.close()
print('----------------')
res = open('aa.txt', 'r')
content = res.readlines()  # Read all by default
print(content)
# Close file
res.close()

If the readLines method reads a large file, there is a problem

  • readline()
    readline() reads one line at a time.
f = open('test.txt') 
content = f.readline() 
print(f'First line:{content}') 
content = f.readline() 
print(f'Second line:{content}')
# Close file 
f.close()
  1. seek()
    Function: used to move the file pointer.
    The syntax is as follows:
File object.seek(Offset, Starting position)

Starting position:

  • 0: beginning of file
  • 1: Current location
  • 2: End of file
  1. close
File object.close()

Posted by jmac2501 on Sat, 18 Sep 2021 21:41:39 -0700