2016-06-14 25 views
1

Ich bin ein Problem mit functools.partial.Python: functools.partial gibt Fehler

Mein Code:

selected_words = ['awesome', 'great', 'fantastic', 'amazing', 'love', 'horrible', 'bad', 'terrible', 'awful', 'wow', 'hate'] 

def awsome_count(x,i): 
    if selected_words[i] in x: 
     y=1 
    else: 
     y=0 
    return y 

partialfun=functools.partial(awsome_count,0) 

partialfun(products[2]['word_count']) 

products ist ein SFrame.

Fehler:

TypeError         Traceback (most recent call last) 
<ipython-input-108-e51348a5d1f0> in <module>() 
----> 1 partialfun(products[2]['word_count']) 

<ipython-input-66-9ba8c7128add> in awsome_count(x, i) 
     1 def awsome_count(x,i): 
----> 2  if selected_words[i] in x: 
     3   y=1 
     4  else: 
     5   y=0 

TypeError: list indices must be integers, not dict 

I partial Funktion verwende, ist, weil ich apply Funktion verwenden möchten:

products['word_count'].apply(functools.partial(awsome_count,0) 

Antwort

3

Du hast dein partial() Objekt ein Positions Argument:

functools.partial(awsome_count, 0) 

Dieses Argument wird angewendet zuerst; zusätzliche Positions Argumente zu, dass man hinzugefügt, so dass Ihr Anruf:

partialfun(products[2]['word_count']) 

werden:

awesome_count(0, products[2]['word_count']) 

, die die falsche Reihenfolge für Ihre Funktion ist.

Wenn Sie einen Standardwert für das i Argument Ihrer Funktion anwenden möchten, verwenden Sie ein Schlüsselwort-Argument anstelle eines Positions Argument:

partialfun = functools.partial(awsome_count, i=0) 

nun der Ruf partialfun(products[2]['word_count']) wird

awsome_count(products[2]['word_count'], i=0) 
+0

Hey, Die Antwort ist definitiv hilfreich. Ich habe gerade gewählt, bin mir nicht sicher, ob ich gerade jetzt falsch abstimme. Das tut mir leid. – alan

+0

Keine Sorge, es kann nicht Sie gewesen sein, da Sie nicht ablehnen können, bis Sie 125 Punkte oder mehr haben. :-) –