I have a list in python:
A = ['5', 'C', '1.0', '2.0', '3.0', 'C', '2.1', '1.0', '2.4', 'C', '5.4', '2.4', '2.6', 'C', '2.3', '1.2', '5.2']
I want to join A in a a way where output looks like:
5\n
C 1.0 2.0 3.0\n
C 2.1 1.0 2.4\n
C 5.4 2.4 2.6\n
C 2.3 1.2 5.2
''.join(A) joins every string together, '\n'.join(A) joins every string starting from new line. Any help for this? Thanks!
You can loop through, or just do something like this:
' '.join(A).replace(' C', '\nC')
The space in the replace string is really important to prevent a leading empty line if the first char is a 'C', and to prevent trailing whitespace in other places. (Thanks @aruisdante)
I'd probably employ some itertools functionality.
from itertools import izip
def chunks(iterable, num=2):
it = iter(iterable)
return izip(*[it] * num)
print '\n'.join([A[0]] + [' '.join(c) for c in chunks(A[1:], 4)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With