Welcome, guest | Sign In | My Account | Store | Cart

I was looking at some word count code and thought a more functional approach would be better and more fun to code.

Python, 1 line
1
lengths = map(lambda word: len(word), open("foo.txt","r").readline().split())

This method was used for its simplicity.

2 comments

James Mills 11 years, 1 month ago  # | flag

An even better approach is to simply do this:

from itertools import chain
lengths = list(chain(*list(list(len(word) for word in line.split()) for line in open("foo.txt", "r"))))

:)

--JamesMills / prologic

James Mills 11 years, 1 month ago  # | flag

Actually I'm stupid :) Just:

from itertools import chain
lengths = list(chain(*((len(word) for word in line.split()) for line in open("foo.txt", "r"))))

:)

Created by Michael Thamm on Tue, 26 Feb 2013 (MIT)
Python recipes (4591)
Michael Thamm's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks