2016-04-26 11 views
1

私は単語のリストを持っています。私は最小の長さを持っていない単語を除外したいと思います。フィルターをかけましたが、何らかのエラーが表示されました。フィルタを使用するときに関数に2つの引数を渡す

from functools import partial 

z = filter(partial(words_to_integer, y=minimumlength), listofwords) 

partial(words_to_integer, y=minimumlength)words_to_integerと同じ機能ですが、引数yminimumlengthに固定されている:私のコードは、エラーがあなたがfunctools.partialをご覧ください

z = list(filter(words_to_integer,(listofwords,minimumlength))) 
TypeError: words_to_integer() missing 1 required positional argument: 'y' 

答えて

2

ある

def words_to_integer(x,y): 
      return len(x)> y 


print("enter the list of words : ") 
listofwords = [ str(x) for x in input().split()] #list of words 
minimumlength = print("enter the length ")   
z = list(filter(words_to_integer,(listofwords,minimumlength))) 

print("words with length greater than ",minimumlength ,"are" ,z) 

です。

0

これはできません。既に最小長を知っている関数を渡す必要があります。

スタンドアロン機能の代わりにラムダを使用することですこれを行う1つの簡単な方法:

filter(lambda x: len(x) > minimumlength, listofwords) 
0

あなたはこの

list(filter(words_to_integer,(listofwords,minimumlength))) 

Pythonはこのような何かをしようと入力すると:

z = [] 
if words_to_integer(listofwords): 
    z.append(listofwords) 
if words_to_integer(minimumlength): 
    z.append(minimumlength) 

words_to_integerは2つの引数を受け入れるため失敗しますが、givは1つだけですen。

z = [] 
for word in listofwords: 
    if words_to_integer(word): 
     z.append(word) 

filterで、次のようになります:

は、おそらくこのような何かをしたい

z = list(filter(lambda word: words_to_integer(word, minimumlength), listofwords)) 

または他の回答のようにpartialを使用しています。

関連する問題