How to iterate the input over a particular size?

Francesco Bochicchio bieffe62 at gmail.com
Mon Dec 28 03:58:28 EST 2009


On 27 Dic, 22:29, joy99 <subhakolkata1... at gmail.com> wrote:
> On Dec 27, 8:42 pm, Benjamin Kaplan <benjamin.kap... at case.edu> wrote:
>
>
>
> > On Sun, Dec 27, 2009 at 9:44 AM, joy99 <subhakolkata1... at gmail.com> wrote:
> > > Dear Group,
>
> > > I am encountering a small question.
>
> > > Suppose, I write the following code,
>
> > > input_string=raw_input("PRINT A STRING:")
> > > string_to_word=input_string.split()
> > > len_word_list=len(string_to_word)
> > > if len_word_list>9:
> > >             rest_words=string_to_word[9:]
> > >             len_rest_word=len(rest_words)
> > >             if len_rest_word>9:
> > >                      remaining_words=rest_words[9:]
>
> > > In this program, I am trying to extract first 9 words from an
> > > indefinitely long string, until it reaches 0.
> > > Am I writing it ok, or should I use while, or lambda?
> > > If any one can suggest.
>
> > > Hope you are enjoying a nice vacation of Merry Christmas. If any one
> > > is bit free and may guide me up bit.
>
> > > Wishing you a happy day ahead,
> > > Best Regards,
> > > Subhabrata.
> > > --
>
> > You want the first 9 words? string_to_word[:9]
> > You want the last 9 words? string_to_word[-9:]
>
> > If you want the groups of words, use a loop- that's the only way to
> > get all of them for any length list.
>
> > >http://mail.python.org/mailman/listinfo/python-list-Hide quoted text -
>
> > - Show quoted text -- Hide quoted text -
>
> > - Show quoted text -
>
> Dear Group,
> Answers were good. But I am looking for a smarter solution like:
>
> for i[:2] in list:
> ....
>
> etc. or by doing some looping over loop.
> Do not worry I'll work out the answer.
>
> Wishing you a happy day ahead,
> Regards,
> Subhabrata.

Not sure I understood your question, but if you need just to plit a
big list in sublists of no more than 9 elements, then you can do
someting like:

def sublists(biglist, n ):
        "Splits a big list in sublists of max n elements"
	prev_idx = 0; res = []
	for idx in xrange(n, len(biglist)+n, n ):
		res.append( biglist[prev_idx:idx] )
		prev_idx = idx
	return res

I would not be surprised if somewhere in python standard library there
is something like this (possibly better), but
could not find anything.

Another solution could be this smarter-looking but less readeable one
liner:

        sublists = [ big_list[i:(i+9)] for i in xrange( 0, len
(big_list)+9, 9) if i < len(big_list) ]


P.S : if your biglist is huge (but being typed in I don't think so)
then you better convert the "sublists" function in a
generator.


HTH

Ciao
----
FB



More information about the Python-list mailing list