3

I have a list of pairs to convert to strings (for later printing) and I want to insert a \n every three pairs. I could do as in my following sample code, but is there a more compact way in Python?

pairs = [[1,2] for i in range(10)] #my data
pairs = [str(p) + ', ' for p in pairs]
for i in reversed(range(0, len(pairs), 3)):
    if i == 0:
        continue
    pairs.insert(i, '\n')
pairs = ''.join(pairs)
pairs = pairs [:-2] #removing the last ', '

This way, I get:

>>> print pairs
[1, 2], [1, 2], [1, 2], 
[1, 2], [1, 2], [1, 2], 
[1, 2], [1, 2], [1, 2], 
[1, 2]

1 Answer 1

3

Possibly use a helper generator that yields the values from pairs, and a '\n' after every three:

def add_after_every_n(iterator, item_to_add='\n', after_every=3):
    for i, element in enumerate(iterator, 1):  # i counts from 1
         yield element
         if i % after_every == 0:
            yield item_to_add

pairs = [[1,2] for i in range(10)]
pairs = [str(p) + ', ' for p in pairs]
pairs_string = ''.join(add_after_every_n(pairs))
pairs_string = pairs_string[:-2]  # remove last ', '
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.