本帖最后由 yottaWind 于 2024-11-12 12:11 编辑
python的简洁性在于,其有很多的原生函数,可以用于简化代码,下面是一些分类介绍,代码附在最下方
学会使用下面这些函数可以使你的代码更加优雅
- iter(): 返回迭代器对象
- next(): 返回迭代器的下一个项目
- map(): 对序列执行函数操作
- filter(): 过滤序列
- zip(): 聚合多个序列
- lambda: 创建匿名函数
- reduce(): 对序列累积操作
- partial(): 固定函数参数
- property(): 将方法转为属性
- staticmethod(): 静态方法装饰器
- classmethod(): 类方法装饰器
- getattr(): 获取对象属性
- setattr(): 设置对象属性
- hasattr(): 检查对象属性
- callable(): 检查对象是否可调用
- enumerate(): 返回索引序列
- reversed(): 反转序列
- sorted(): 排序
- any()/all(): 检查真值
- isinstance(): 类型检查
- issubclass(): 检查类继承关系
1.迭代器相关函数:
[Python] 纯文本查看 复制代码
# iter() 和 next()
my_list = [1, 2, 3]
iterator = iter(my_list)
print(next(iterator)) # 1
print(next(iterator)) # 2
# map()
numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # [1, 4, 9, 16]
# filter()
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(is_even, numbers)
print(list(evens)) # [2, 4, 6]
# zip()
names = ['Alice', 'Bob']
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age}") # Alice is 25, Bob is 30
2.函数式编程:
[Python] 纯文本查看 复制代码
# lambda
square = lambda x: x**2
print(square(4)) # 16
# reduce
from functools import reduce
numbers = [1, 2, 3, 4]
sum_all = reduce(lambda x, y: x + y, numbers)
print(sum_all) # 10
# partial
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, 2)
print(double(4)) # 8
3.装饰器相关:
[Python] 纯文本查看 复制代码
class Person:
def __init__(self):
self._age = 0
@property
def age(self):
return self._age
@staticmethod
def static_method():
print("This is a static method")
@classmethod
def class_method(cls):
print("This is a class method")
4.反射相关
[Python] 纯文本查看 复制代码
class Test:
def __init__(self):
self.name = "test"
obj = Test()
# getattr
print(getattr(obj, 'name')) # "test"
# setattr
setattr(obj, 'age', 25)
print(obj.age) # 25
# hasattr
print(hasattr(obj, 'name')) # True
# callable
def func():
pass
print(callable(func)) # True
5.序列操作
[Python] 纯文本查看 复制代码
# enumerate
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# reversed
for char in reversed("hello"):
print(char) # o l l e h
# sorted
numbers = [3, 1, 4, 1, 5]
print(sorted(numbers)) # [1, 1, 3, 4, 5]
# any/all
numbers = [1, 2, 3, 4, 5]
print(any(x > 3 for x in numbers)) # True
print(all(x > 3 for x in numbers)) # False
6.类型检查
[Python] 纯文本查看 复制代码
# isinstance
print(isinstance(42, int)) # True
print(isinstance("hello", str)) # True
# issubclass
class Animal: pass
class Dog(Animal): pass
print(issubclass(Dog, Animal)) # True
|