Questions: While And List Comprehension

r0g aioe.org at technicalbloke.com
Thu Nov 11 01:04:54 EST 2010


On 10/11/10 22:56, Emile van Sebille wrote:
> On 11/10/2010 4:36 AM Felipe Vinturini said...
>> Hi Folks,
>>
>> I am quite new to python and I don't have a lot of experience with it
>> yet.
>>
>> I have two simple questions:
>>
>> 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
>
> Easiest would be print [ v for v in sys.stdin.readlines()[:5] ] but that
> still reads the entire sys.stdin (whatever it may be...)
>


Use readline() + a counter instead...

print [sys.stdin.readline() for x in xrange(0,5)]

Roger



More information about the Python-list mailing list