1、sh
sh库可用来代替使用标准的 os 和 subprocess 库。
#SH库让你可以像调用普通函数一样调用任何程序——对于自动化工作流和任务非常有用
import sh
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')
2、压缩函数zip
该zip()内置函数需要一系列可迭代的对象,并返回一个元组列表中。每个元组按位置索引对输入对象的元素进行分组。还可以通过调用对象来“解压缩”对象*zip()。同时遍历两个或多个列表时,此函数很有用。
#两个列表形成一个字典
keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for x, y in zip(list1, list2):
print(x, y)
# 1 a
# 2 b
# 3 c
3、repr
在 Python 中定义类或对象时,提供一种将该对象表示为字符串的“官方”方式很有用
>>> file = open('file.txt', 'r')
>>> print(file)
<open file 'file.txt', mode 'r' at 0x10d30aaf0>
class someClass:
def __repr__(self):
return "<some description here>"
someInstance = someClass()
# 打印 <some description here>
print(someInstance)
4、枚举函数enumerate
enumerate()函数向可迭代对象添加一个计数器,并以枚举对象的形式返回。当你想要遍历列表并跟踪索引时,此函数很有用。
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(index, fruit)
# 0 apple
# 1 banana
#2 mango
5、匿名函数Lambda
Lambda 函数是使用lambda关键字定义的匿名函数。编写一次性的小函数并且不想使用关键字def来定义命名函数
add = lambda x, y: x + y
result = add(3, 4)
print(result)
# 7
6、装饰器@符号
装饰器是一种修改函数或类行为的方法。使用@符号进行定义,可用于向函数添加功能,例如日志记录、计时或身份验证。
def log_function(func):
def wrapper(*args, **kwargs):
print(f'Running {func.__name__}')
result = func(*args, **kwargs)
print(f'{func.__name__} returned {result}')
return result
return wrapper
@log_function
def add(x, y):
return x + y
print(add(5,7))
7、多个函数参数
在 Python 中,可以使用*和 **运算符来处理多个函数参数。*运算符用于将参数列表作为单独的位置参数进行传递,运算符**用于传递关键字参数的字典。
def print_arguments(*args, **kwargs):
print(args)
print(kwargs)
print_arguments(1, 2, 3, name='John', age=30)
# (1, 2, 3)
# {'name': 'John', 'age': 30}
8、动态导入
当你想根据用户输入或配置导入模块时,可以使用模块动态导入模块importlib。
import importlib
module_name = 'math'
module = importlib.import_module(module_name)
result = module.sqrt(9)
9、快速合并两个字典
dictionary_one = {"a": 1, "b": 2}
dictionary_two = {"c": 3, "d": 4}
merged = {**dictionary_one, **dictionary_two}
print(merged)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
10、列表、集合和字典是可变的
可以更改或更新对象(列表、集合或字典),而无需更改内存中对象的指针。ID(对象指针)
cities = ["Munich", "Zurich", "London"]
print(id(cities)) # 2797174365184
cities.append("Berlin")
print(id(cities)) # 2797174365184
11、获取当前文件所在的文件夹的路径
import os
print(os.path.dirname(os.path.abspath(__file__)))