Python有几个内置的函数和构造,可以被外部库替换或增强,用于调试、日志记录或提高可读性和灵活性。
print()-> iceclamp.ic()
print()函数可以用icecon.ic()代替,以便更好地调试。ic()添加了额外的信息,如变量名及其值,沿着调用它的代码行,使跟踪代码执行更容易。
from icecream import ic
def func():
x = 10
y = 20
ic(x, y) # This will print the variable names and values
result = x + y
ic(result) # It also prints the result of the operation
func()
open()-> pathlib.Path().open()
Python内置的open()函数可以被pathlib.Path().open()替换,以更好地处理文件路径和文件操作,因为pathlib()提供了一种面向对象的方法来处理文件路径。
from pathlib import Path
# Instead of open('file.txt', 'r')
path = Path('file.txt')
with path.open('r') as file:
content = file.read()
range()-> itertools.count()
如果您正在处理无限循环或需要序列生成器,则可以将range()替换为itertools.count(),以生成无限的数字序列。
import itertools
# Instead of range(10)
for num in itertools.count(start=0, step=1):
if num == 10:
break
print(num)
map()、filter()、reduce()->列出解析或生成器表达式
# Instead of map(lambda x: x * 2, list)
doubled = [x * 2 for x in list]
# Instead of filter(lambda x: x > 0, list)
positive_numbers = [x for x in list if x > 0]
from functools import reduce
# Instead of reduce(lambda x, y: x + y, list)
sum_of_numbers = sum(list)
try...except -> contextlib.suppress()
如果您要在try. except块中抑制特定的异常,则可以使用contextlib.suppress()以更简洁的方式抑制异常。
from contextlib import suppress
# Instead of try-except:
# try:
# foo()
# except SomeException:
# pass
with suppress(SomeException):
foo()
sorted()→ heapq. nminimum()或heapqnlargest()
如果您只需要列表中最小或最大的项,而不是对整个列表进行排序,则可以使用heapq. nsminimum()或heapqnlargest()来获得更好的性能。
import heapq
# Instead of sorted(list) to get the smallest 3 elements
smallest_three = heapq.nsmallest(3, list)
collections.Counter()→ pandas.value_counts()
如果你使用collections.Counter()来计算列表中的元素,并且你正在处理可以表示为表的数据(例如,a DataFrame),您可以使用pandas.value_counts()来获得更强大、更高效的解决方案。
import pandas as pd
# Instead of collections.Counter
counts = pd.Series([1, 2, 2, 3, 3, 3]).value_counts()
Python有许多函数可以用第三方库替换或增强,通常提供更好的功能,更容易使用和额外的功能。选择正确的工具取决于您的特定需求,无论是调试、日志记录、文件处理还是处理数据。