A Little Noise

December 13, 2019

Using map with class methods – why map(split) doesn’t work

Filed under: Python,Technical — snoyes @ 11:19 am

I have some sentences.

text = [
  "Call me Ishmael.",
  "Some years ago, never mind how long precisely, having little or no money..."
]

How many words are in each sentence?

for sentence in text:
  sentenceLength = len(sentence.split())
  print(sentenceLength)

3
13

But I want to do it all at once the functional programming way, with maps.

list(map(len, map(split, text)))

NameError: name 'split' is not defined

Why does that produce an error? Because “split” isn’t a function. It’s a method of strings: str.split(), not split(str).

So how do we use map with a class method?

from operator import methodcaller
split = methodcaller("split")

That means, “Create a function. I’ll pass in an object. Call its ‘split’ method.”

Now it works.

list(map(len, map(split, text)))
[3, 13]

Of course, there are other ways. Don’t even need map.

[len(s.split()) for s in text]

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress