Questions: While And List Comprehension
James Mills
prologic at shortcircuit.net.au
Wed Nov 10 19:29:04 EST 2010
On Thu, Nov 11, 2010 at 8:56 AM, Emile van Sebille <emile at fenx.com> wrote:
> Easiest would be print [ v for v in sys.stdin.readlines()[:5] ] but that
> still reads the entire sys.stdin (whatever it may be...)
Here's a way of doing the same thing without consuming the entire
stream (sys.stdin):
#!/usr/bin/env python
import sys
print [v for v in list(line for line in sys.stdin)[:5]]
This uses a generator expression to read from stdin, converts this to
a list (only getting the first 5 items).
cheers
James
--
-- James Mills
--
-- "Problems are solved by method"
More information about the Python-list
mailing list