Reputation: 47
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!
Upvotes: 3
Views: 113
Reputation: 14854
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)
Upvotes: 8
Reputation: 11915
Without any imports:
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']
B = []
j = 0
for i, a in enumerate(A):
if a == 'C':
B.append(A[j:i])
j = i
B.append(A[j:])
print(("\n".join(" ".join(b) for b in B)))
Upvotes: 0
Reputation: 48038
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)])
Upvotes: 2