目录
方法2:列表推导式: result = [x + 1 for x in numbers]
方法9:使用 itertools 的 starmap(需重组数据)
方法10:使用 collections.deque 的 extend 方法(非典型用法)
方法12: 使用 bytearray 的原地修改(仅限小整数)
方法13:函数式组合:reduce + lambda(累积构建列表)
方法14:使用 exec 动态生成代码(仅用于演示,不推荐实际使用)
方法16: 使用 threading 多线程(过度设计,仅演示)
我在前面说过内置函数了,有不明白的点进去就好了。因为我们前面已经学习了很多。所以捏,我今天打算尽量一题多解,让我们知道该怎么写,怎么用。
1、使用map函数将一个列表中的所有数字加1
方法1:使用map()函数
numbers = [1, 2, 3, 4, 5]
# 要求:使用map函数,将列表中的每个数字都加1,输出结果
result = list(map(lambda x: x + 1, numbers))
print(result)
方法2:列表推导式: result = [x + 1 for x in numbers]
使用operator.add
: 结合functools.partial
固定参数:
from operator import add
from functools import partial
add_one = partial(add, 1)
result = list(map(add_one, numbers))
方法3:使用 functools.partial
固定参数
结合 operator.add
函数,通过固定第一个参数为 1
,生成一个专门用于加1的函数:
from operator import add
from functools import partial
numbers = [1, 2, 3, 4, 5]
add_one = partial(add, 1) # 固定第一个参数为1,得到等价于 lambda x: 1 + x
result = list(map(add_one, numbers))
print(result) # 输出 [2, 3, 4, 5, 6]
方法4:使用 numpy
库(适用于数值计算)
如果处理大规模数值数据,numpy
的向量化操作更高效:
import numpy as np
numbers = [1, 2, 3, 4, 5]
arr = np.array(numbers)
result = (arr + 1).tolist() # 直接对数组整体加1
print(result) # 输出 [2, 3, 4, 5, 6]
方法5:生成器表达式(延迟计算)
与列表推导式类似,但生成器按需计算,节省内存:
numbers = [1, 2, 3, 4, 5]
gen = (x + 1 for x in numbers) # 生成器表达式
result = list(gen) # 转换为列表
print(result) # 输出 [2, 3, 4, 5, 6]
方法6:递归函数(教学示例,非实际推荐)
虽然不适用于简单操作,但演示递归思想:
def add_one_recursive(lst):
if not lst:
return []
return [lst[0] + 1] + add_one_recursive(lst[1:])
numbers = [1, 2, 3, 4, 5]
result = add_one_recursive(numbers)
print(result) # 输出 [2, 3, 4, 5, 6]
方法7:类方法封装
通过类将加1操作封装为方法:
class NumberProcessor:
def __init__(self, numbers):
self.numbers = numbers
def increment(self, value=1):
return [x + value for x in self.numbers]
numbers = [1, 2, 3, 4, 5]
processor = NumberProcessor(numbers)
result = processor.increment(1) # 加1
print(result) # 输出 [2, 3, 4, 5, 6]
方法8:使用 pandas
库(表格数据处理)
如果数据来自表格或需要复杂处理,pandas
提供便捷操作:
import pandas as pd
numbers = [1, 2, 3, 4, 5]
series = pd.Series(numbers)
result = (series + 1).tolist()
print(result) # 输出 [2, 3, 4, 5, 6]
方法9:使用 itertools
的 starmap
(需重组数据)
虽然 starmap
通常用于展开元组参数,但可通过包装实现类似效果:
from itertools import starmap
numbers = [1, 2, 3, 4, 5]
result = list(starmap(lambda x: x + 1, zip(numbers))) # zip(numbers)将元素转为单元素元组
print(result) # 输出 [2, 3, 4, 5, 6]
方法10:使用 collections.deque
的 extend
方法(非典型用法)
利用双端队列的可迭代扩展特性,结合生成器:
from collections import deque
numbers = [1, 2, 3, 4, 5]
result = deque()
result.extend(x + 1 for x in numbers) # 生成器直接扩展队列
print(list(result)) # 输出 [2, 3, 4, 5, 6]
方法11:利用 __add__
方法的重载
通过自定义类重载加法运算符,实现元素级加法:
class AddableNumber(int):
def __add__(self, other):
return AddableNumber(super().__add__(other))
numbers = [AddableNumber(x) for x in [1, 2, 3, 4, 5]]
result = [x + 1 for x in numbers] # 每个元素实际是自定义类的实例
print(result) # 输出 [2, 3, 4, 5, 6]
方法12: 使用 bytearray
的原地修改(仅限小整数)
注意:仅适用于元素值在 0~255 的整数,通过二进制直接操作:
numbers = [1, 2, 3, 4, 5]
barr = bytearray(numbers)
for i in range(len(barr)):
barr[i] += 1 # 原地修改字节数组
print(list(barr)) # 输出 [2, 3, 4, 5, 6]
方法13:函数式组合:reduce
+ lambda
(累积构建列表)
虽然 reduce
通常用于累积计算,但可以强行用它生成列表:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda lst, x: lst + [x + 1], numbers, [])
print(result) # 输出 [2, 3, 4, 5, 6]
方法14:使用 exec
动态生成代码(仅用于演示,不推荐实际使用)
通过字符串生成代码并执行:
numbers = [1, 2, 3, 4, 5]
code = "result = [x + 1 for x in numbers]"
exec(code, globals(), locals())
print(locals()['result']) # 输出 [2, 3, 4, 5, 6]
方法15:协程与 send
方法(异步风格)
利用协程逐个处理元素:
def number_processor():
result = []
while True:
x = yield
result.append(x + 1)
return result
numbers = [1, 2, 3, 4, 5]
coroutine = number_processor()
next(coroutine) # 启动协程
for x in numbers:
coroutine.send(x)
try:
coroutine.send(None) # 触发结束
except StopIteration as e:
print(e.value) # 输出 [2, 3, 4, 5, 6]
方法16: 使用 threading
多线程(过度设计,仅演示)
虽然加1操作极快,但可以强行用线程池处理:
from concurrent.futures import ThreadPoolExecutor
numbers = [1, 2, 3, 4, 5]
with ThreadPoolExecutor() as executor:
result = list(executor.map(lambda x: x + 1, numbers))
print(result) # 输出 [2, 3, 4, 5, 6]
方法17:装饰器增强函数(间接实现)
定义一个装饰器来包装加法操作:
def add_decorator(n):
def decorator(func):
def wrapper(x):
return func(x) + n
return wrapper
return decorator
@add_decorator(1)
def identity(x):
return x
numbers = [1, 2, 3, 4, 5]
result = list(map(identity, numbers))
print(result) # 输出 [2, 3, 4, 5, 6]
方法18:使用 ast
模块操作语法树(极端方法)
通过修改抽象语法树动态生成代码:
import ast
class AddOneTransformer(ast.NodeTransformer):
def visit_List(self, node):
new_elts = [ast.BinOp(op=ast.Add(), left=elt, right=ast.Constant(value=1))
for elt in node.elts]
return ast.List(elts=new_elts, ctx=ast.Load())
code = "[1, 2, 3, 4, 5]"
tree = ast.parse(code, mode='eval')
transformer = AddOneTransformer()
new_tree = transformer.visit(tree)
result = eval(compile(new_tree, filename="<ast>", mode="eval"))
print(result) # 输出 [2, 3, 4, 5, 6]