Reputation: 391
I have a list of words . I wants to filter out words which do not have minimum length. I tried filter, but showing some error . My code is
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 )
error is
z = list(filter(words_to_integer,(listofwords,minimumlength)))
TypeError: words_to_integer() missing 1 required positional argument: 'y'
Upvotes: 1
Views: 83
Reputation: 5458
When you type this
list(filter(words_to_integer,(listofwords,minimumlength)))
python tries to do something like this:
z = []
if words_to_integer(listofwords):
z.append(listofwords)
if words_to_integer(minimumlength):
z.append(minimumlength)
which will fail, because words_to_integer
accepts 2 arguments, but only one was given.
You probably want something like this:
z = []
for word in listofwords:
if words_to_integer(word):
z.append(word)
which looks like this with filter
:
z = list(filter(lambda word: words_to_integer(word, minimumlength), listofwords))
or use partial
like in the other answer.
Upvotes: 0
Reputation: 600059
You can't do that. You need to pass a function that already knows about minimumlength.
One easy way to do this would be to use a lambda instead of your standalone function:
filter(lambda x: len(x) > minimumlength, listofwords)
Upvotes: 0
Reputation: 73498
You should look at functools.partial
:
from functools import partial
z = filter(partial(words_to_integer, y=minimumlength), listofwords)
partial(words_to_integer, y=minimumlength)
is the same function as words_to_integer
, but with argument y
being fixed at minimumlength
.
Upvotes: 2