Reputation: 122092
I have a function to measure text length:
def length(text, option='char'):
if option == 'char':
return len(text) - text.count(' ')
elif option == 'token':
return text.count(' ') + 1
I can get the character text length:
texts = ['this is good', 'foo bar sentence', 'hello world']
text_lens = map(length, texts)
print text_lens
But how do i specify the 2nd parameter in the function when i'm using map
?
The following code:
texts = ['this is good', 'foo bar sentence', 'hello world']
text_lens = map(length(option='token'), texts)
print text_lens
gives this error:
TypeError: length() takes at least 1 argument (1 given)
Upvotes: 2
Views: 94
Reputation: 40713
In most cases a list comprehension / generator is preferable to map
. It offers all the power of map with a couple of added features.
text_lens = [length(item, option="token") for item in texts]
Upvotes: 2
Reputation: 369134
Alternatively, you can use lambda
:
text_lens = map(lambda x: length(x, 'token'), texts)
text_lens = map(lambda x: length(x, option='token'), texts)
Upvotes: 2
Reputation: 129001
Use functools.partial
:
text_lens = map(functools.partial(length, option='token'), texts)
Upvotes: 3