[Tutor] Iterate Suggestion
Bod Soutar
bodsda at googlemail.com
Sat Apr 14 19:33:10 CEST 2012
On 14 April 2012 18:29, Bod Soutar <bodsda at googlemail.com> wrote:
>
>
> On 14 April 2012 16:27, Tom Tucker <tktucker at gmail.com> wrote:
>
>>
>> Hello all. Any suggestions how I could easily iterate over a list and
>> print the output 3 across (when possible)? One method I was considering
>> was removing the recently printed item from the list, checking list length,
>> etc. Based on the remaining length of the list I would then print X
>> across. Yah? Is their and easier approach I might be overlooking?
>>
>>
>> For example...
>>
>> mylist = ['serverA', 'serverB', 'serverC', 'serverD',' serverE',
>> 'serverF', 'serverG']
>>
>>
>> Desired Output
>> ============
>> serverA serverB serverC
>> serverD serverE serverF
>> serverG
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> How about something like this
>
>
> mylist = ['serverA', 'serverB', 'serverC', 'serverD','serverE',
> 'serverF', 'serverG']
> tempstr = ""
> count = 0
>
> for item in mylist:
> count += 1
> if count == 3:
> tempstr += (i + "\n")
> count = 0
> else:
> tempstr += (i + " ")
>
> print tempstr
>
>
> The above code prepares an empty string variable, and a count variable. On
> each iteration, it checks to see if the count is equal to 3. If it is, then
> it appends the current list element to the string and also adds a newline
> character("\n"), then the count is reset to 0. If the count isn't 3, it
> simply appends the current list element along with a space.
>
> Hope this helps,
> Bodsda
>
>
> erm, I screwed up my variable names. where you see 'i', this should be
item (or the other way around).
My bad.
-- Bodsda
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120414/0bdbf71b/attachment.html>
More information about the Tutor
mailing list