Skip to main content
 首页 » 编程设计

python之是否有重复重新分配变量的简写

2025年04月02日13itcoder

考虑这个例子:

x = 27 
x = sqr(x) 
x += 2 
x = x * 0.1 

这可以简单地简化为

x = 0.1 * (sqr(27) + 2) 

现在,考虑(x 作为 OrderedDict)

x = {k: bubble_sort(v) for k, v in x.items()} 
 
x = {k: rename(k) for k, v in x.items()} 
 
x = {k: abs(k) for k, v in x.items()} 

是否有避免重复变量赋值的速记技巧?例如,是否有这样的函数:

def pipeline(x, function_handles): 
    .... 
    for f in function_handles: 
        x.apply(f) #in place 
return x 

或

def pipeline(x, expression): 
    .... 
    for ex in expression: 
        ex(x) #in place 
return x 

请您参考如下方法:

在 operator 模块中有 operator.methodcaller功能。它的工作方式类似于 itemgetter,这是您最有可能已经见过的一种:给定一个名称, methodcaller 的返回值是部分的调用其参数的命名方法的函数。

即给定:

x = SomeObjectType() 
f = operator.methodcaller('amethod', 'arg1', arg2=100) 
f(x) 

等同于说:

x = SomeObjectType() 
x.amethod('arg1', arg2=100) 

您可以将其与简单的 lambda 表达式和/或 functools.partial 一起使用或 partial_method 构建要应用的函数/方法列表。然后,按照@cricket_007 的建议,您可以使用或编写代码来自动应用它们。

另外值得注意的是 functools.reduce。您可以编写或构建调用函数,然后使用 reduce 为其提供要调用的函数列表。

下面是一些根据数据列表减少函数列表的代码(py3,但适用于 2.7):

#!python3 
import functools 
import itertools 
import operator 
 
data = [8, 6, 7, 5, 3, 0, 9] 
 
def apply(val, fn): 
    print("F=",fn, "val=",val) 
    return fn(val) 
 
 
from functools import reduce 
 
fns = [sorted, 
        max, 
        str, 
    ] 
 
print(reduce(apply, fns, data))