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

时间:2016-06-03 21:15:15

标签: python python-2.7

考虑一下这个例子:

let objArr = [
  {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 42},
  {key: 'Mon Sep 24 2013 00:00:00 GMT-0400', val: 78},
  {key: 'Mon Sep 25 2013 00:00:00 GMT-0400', val: 23},
  {key: 'Mon Sep 23 2013 00:00:00 GMT-0400', val: 54}
];

// first, convert data into a Map with reduce
let counts = objArr.reduce((prev, curr) => {
  let count = prev.get(curr.key) || 0;
  prev.set(curr.key, curr.val + count);
  return prev;
}, new Map());

// then, map your counts object back to an array
let reducedObjArr = [...counts].map(([key, value]) => {
  return {key, value}
})

console.log(reducedObjArr);

这可以简单地减少到

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

现在,考虑(x作为OrderedDict)

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

是否有速记技巧以避免重复变量赋值?例如,是否有一个函数:

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

1 个答案:

答案 0 :(得分:1)

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.partialpartial_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))
相关问题