Questions: While And List Comprehension

Steve Holden steve at holdenweb.com
Wed Nov 10 19:57:29 EST 2010


On 11/10/2010 6:01 PM, James Mills wrote:
> On Wed, Nov 10, 2010 at 10:36 PM, Felipe Vinturini
> <felipe.vinturini at gmail.com> wrote:
>> 1. Is there a way to limit the number of times a list comprehension will
>> execute? E.g. I want to read from input only 5 values, so I would like
>> something like (the values between # # are what I want):
>> ===================================================================================
>> COUNT = 0
>> print [ v for v in sys.stdin.readlines() # IF COUNT < 5 # ] ## Increment
>> COUNT somewhere
>> ===================================================================================
> 
> print [v for v in sys.stdin.readlines()[:5]]
> 
how about print [sys.stdin.readline() for i in range(5)]

At least that won't consume the whole file.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17       http://us.pycon.org/
See Python Video!       http://python.mirocommunity.org/
Holden Web LLC                 http://www.holdenweb.com/




More information about the Python-list mailing list