Reputation: 2448
In Python I have this loop that e.g. prints some value:
for row in rows:
toWrite = row[0]+","
toWrite += row[1]
toWrite += "\n"
Now this works just fine, and if I print "toWrite" it would print this:
print toWrite
#result:,
A,B
C,D
E,F
... etc
My question is, how would I concatenate these strings with parenthesis and separated with commas, so result of loop would be like this:
(A,B),(C,D),(E,F) <-- the last item in parenthesis, should not contain - end with comma
Upvotes: 0
Views: 3210
Reputation: 195
Try this:
from itertools import islice, izip
','.join(('(%s, %s)' % (x, y) for x, y in izip(islice(rows, 0, None, 2), islice(rows, 1, None, 2))))
Generator and iterators are adopted here. See itertools for a reference.
Upvotes: 1
Reputation: 1122092
You'd group your items into pairs, then use string formatting and str.join()
:
','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
zip(*[iter(rows)] * 2)
expression produces elements from rows
in pairs.'({},{})'.format(*pair)
; the two values in pair
are slotted into each {}
placeholder.(A,B)
strings are joined together into one long string using ','.join()
. Passing in a list comprehension is marginally faster than using a generator expression here as str.join()
would otherwise convert it to a list anyway to be able to scan it twice (once for the output size calculation, once for building the output).Demo:
>>> rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
>>> ','.join(['({},{})'.format(*pair) for pair in zip(*[iter(rows)] * 2)])
'(A,B),(C,D),(E,F),(G,H)'
Upvotes: 2