18

ラムダまたはリスト内包表記なしでPythonのオブジェクトに関数のリストを適用するきれいな方法はありますか? Haskell 式のように:

map ($ obj) [foo1,foo2]

Python でのラムダの例:

response = map(lambda foo:foo(obj),[foo1,foo2]) #fooX:object->Bool

クラス関数に拡張可能ですか?

おそらく、オペレーターまたは itertools からの何かでしょうか?

4

7 に答える 7

16

あなたはいつでもそれを処理する関数を作成することができます:

def map_funcs(obj, func_list):
    return [func(obj) for func in func_list]

    # I was under the impression that the OP wanted to compose the functions,
    # i.e. f3(f2(f1(f0(obj))), for which the line below is applicable:
    # return reduce(lambda o, func: func(o), func_list, obj)


map_funcs(it, [Buy, Use, Break, Fix])
于 2012-07-31T09:11:30.483 に答える
11

これはあなたの「機能的」基準に合うはずだと思います。あなたの質問に答えるには、きれいな方法はないと思います。内包表記をリストすることに順応する必要があります。

@JFSebastian の提案による

>>> from operator import methodcaller
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> obj = 5
>>> list(map(methodcaller('__call__', obj), funcs))
[6, 7]

これはクレイジーな方法です:

>>> from itertools import starmap, repeat
>>> from types import FunctionType
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> obj = 5
>>> list(starmap(FunctionType.__call__, zip(funcs, repeat(obj))))
[6, 7]

@AleksiTorhamo の提案による

>>> from itertools import repeat
>>> from types import FunctionType
>>> obj = 5
>>> funcs = (lambda x: x + 1, lambda x: x + 2)
>>> list(map(FunctionType.__call__, funcs, repeat(obj)))
[6, 7]
于 2012-07-31T09:24:00.643 に答える
5

リスト内包表記は、あるリストを別のリストに基づいて作成するための最良の方法だと思います。リストから通常の関数を適用するのはとても簡単です:

results = [f(obj) for f in funcList]

一度に結果のリスト全体を必要とせず、一度に 1 つずつアイテムを反復処理する必要がある場合は、ジェネレーター式の方が適している場合があります。

genexp = (f(obj) for f in funcList)
for r in genexp:
    doSomething(r)

関数が基本関数ではなくメソッドである場合、次の 2 つの方法があります。

バインドされたメソッドを使用します。この場合、関数呼び出しを行うときにオブジェクトを提供する必要はまったくありません。

obj = SomeClass()
funcList = [obj.foo1, obj.foo2]
results = [f() for f in funcList]

または、バインドされていないメソッドを使用します。これは、定義されているクラスのインスタンスを最初の引数として期待する単純な通常の関数です (従来は と呼ばれていましたself):

funcList = [SomeClass.foo1, SomeClass.foo2]
obj = SomeClass()
results = [f(obj) for f in funcList]

もちろん、関数の結果を取得する必要がない場合は、単純にループを記述するのが最も簡単です。

for f in funcList:
    f(obj)
于 2012-07-31T09:10:29.300 に答える
0

これが私の解決策です:

def plus(i):
    return i+i

def mult(i):
    return i*4

functions = [plus,mult]

result=[]

for i in ["a","b","c","d"]:
    for j in functions:
        result.append(j(i))

結果 Out[16]: ['aa', 'aaaa', 'bb', 'bbbb', 'cc', 'cccc', 'dd', 'dddd']

于 2019-10-10T17:10:37.107 に答える