Python advanced function 2: use itertools, functools, operator to make the code more efficient, readable and reusable

Python advanced function 2: use itertools, functools, operator to make the code more efficient, readable and reusable

Python is a powerful programming language that provides a wide range of built-in functions and modules to make coding easier and more efficient. The previous blog introduced map, reduce, filter, zip and enumerate ; this blog will introduce itertools.groupby(), functools.partial(), operator.attrgetter() and operator.itemgetter(), and introduce them through practical examples How to use these features to solve real world problems. These functions are very powerful and useful, and can greatly improve your coding ability, as well as make the code more efficient, readable, and reusable.

There are many more powerful functions available in the Python standard library. As a Python developer, you must continue to learn and explore these features to improve your skills and abilities. This way you can write better, more efficient code, and solve more complex problems. Good code isn't just about using high-level functions, it's about writing clean, readable, and well-documented code, and following good coding practices.

The itertools module provides a function called groupby() that allows grouping items in an iterable object according to a key function. This feature is very useful for data analysis and manipulation tasks.

The functools module provides a function called partial() that allows creating a new function with some pre-filled parameters. This function is useful for creating reusable code and simplifying complex function calls.

The operator module provides two functions, called attrgetter() and itemgetter(), that allow easy access to an object's attributes or items. These functions are useful for sorting lists of objects based on their properties or items.

1. Principle

itertools.groupby()

The groupby() function in the itertools module allows grouping items in an iterable object according to a key function. This is useful for data analysis and manipulation tasks. The function takes two arguments: an iterable object and a function to determine the key for each element. The function returns an iterator yielding pairs (key, group), where each group is a sequence of elements with the same key.

functools.partial()

The partial() function in the functools module allows to create a new function pre-filled with some parameters. This is useful for creating reusable code and simplifying complex function calls. This function takes a function and any number of arguments and keyword arguments, and returns a new callable object that, when invoked, applies the original function to the given arguments and keyword arguments, and the values ​​passed to the callable Any other arguments and keyword arguments to the object.

operator.attrgetter() 和 operator.itemgetter()

The attrgetter() and itemgetter() functions in the operator module allow easy access to attributes or items of an object, respectively. Useful for sorting lists of objects based on their properties or items.
The attrgetter() function returns a callable object that, when called, returns the value of the given attribute of the input object. The itemgetter() function returns a callable object that, when called, returns the value of the given item of the input object.

2. Source code

# python高级函数2: itertools、functools、operator
# python python_high2.py

from itertools import groupby

words = ['apple', 'average', 'banana', 'cherry', 'date', 'elderberry', 'fig']

# itertools.groupby() 函数根据键函数对可迭代对象中的项目进行分组。这对于数据分析和操作任务非常有用。该函数有两个参数:一个可迭代对象和一个用于确定每个元素键的函数。该函数返回一个生成对(键、组)的迭代器,其中每个组都是具有相同键的元素序列。下面是如何使用它按第一个字母对单词列表进行分组的示例:
# 该函数按单词的第一个字母对单词进行分组,它首先对单词列表进行排序,然后将 key 函数应用于每个元素以确定作为单词第一个字母的键,然后迭代结果,对于每个键,它返回关联的元素组
for first_letter, group in groupby(sorted(words), key=lambda x: x[0]):
    print(first_letter, list(group))

# functools.partial() functools 模块中的 partial() 函数允许创建一个预填充了一些参数的新函数。这对于创建可重用的代码以及简化复杂的函数调用非常有用。该函数接受一个函数和任意数量的参数和关键字参数,并返回一个新的可调用对象,该对象在调用时,它将原始函数应用于给定的参数和关键字参数,以及传递给可调用对象的任何其他参数和关键字参数。下面是如何使用它创建一个将数字乘以 10 的新函数的示例:
from functools import partial


def multiply(x, y):
    return x * y


# 定义了一个函数乘法,它接受两个参数并返回它们的乘积。然后使用偏函数创建一个新的函数times_10,该函数等效于第一个参数固定为 10 的乘法函数。因此当调用 times_10(5) 时,它相当于调用返回 50 的 multiply(10,5)。
times_10 = partial(multiply, 10)

print(times_10(5))  # 50

# operator.attrgetter() 和 operator.itemgetter() 运算符模块中的 attrgetter() 和 itemgetter() 函数分别允许轻松访问对象的属性或项。对于根据对象的属性或项目对对象列表进行排序非常有用。
# attrgetter() 函数返回一个可调用对象,当调用时,它返回输入对象的给定属性的值。itemgetter() 函数返回一个可调用对象,当调用时,它返回输入对象的给定项的值。下面是如何使用 attrgetter() 按对象名称属性对对象列表进行排序的示例:
import operator


class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


people = [Person('Bob', 30), Person('Charlie', 25), Person('Alice', 35)]

sorted_people = sorted(people, key=operator.attrgetter('name'))

for person in sorted_people:
    print(person.name)

data = [(1, 'a'), (3, 'b'), (2, 'c')]

# 根据第2个属性排序 使用 itemgetter() 函数来获取每个元组的第二项,并将其用作排序的键。
sorted_data = sorted(data, key=operator.itemgetter(1))

for item in sorted_data:
    print(item)

reference

Guess you like

Origin blog.csdn.net/qq_40985985/article/details/130362337