0

I need to print my lists on multiple lines every N element without splitting the original list in smaller lists.

For example, with N = 3

Given this:

MY_LIST = [ 'A', 'B', 'C', 'D', 'E', 'F']

I want python to print THIS:

A B C

D E F

Thank you for your help

3 Answers3

1

You can use itertools.islice and a generator function:

>>> import math
>>> from itertools import islice
def solve(lis, n):                                              
    it = iter(lis)
    le = float(len(lis))
    for _ in xrange(int(math.ceil(le/n))):
        yield " ".join(islice(it, n))

>>> for x in solve([ 'A', 'B', 'C', 'D', 'E', 'F'], 3):
...     print x
...     
A B C
D E F

Using the py3.x's print function:

>>> from __future__ import print_function
>>> print(*solve([ 'A', 'B', 'C', 'D', 'E', 'F'], 3), sep='\n')
A B C
D E F
>>> print(*solve([ 'A', 'B', 'C', 'D', 'E', 'F', 'G'], 3), sep='\n')
A B C
D E F
G
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

try this:

'\n'.join([' '.join(i) for i in zip(*[iter(MY_LIST)]*N)])

Example:

>>> MY_LIST = [ 'A', 'B', 'C', 'D', 'E', 'F']
>>> N=3
>>> '\n'.join([' '.join(i) for i in zip(*[iter(MY_LIST)]*N)])
'A B C\nD E F'
Ofir Israel
  • 3,785
  • 2
  • 15
  • 13
0
>>> for x in (MY_LIST[i:i + N] for i in xrange(0, len(MY_LIST), N)):
...    print " ".join(x)
A B C
D E F
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197