Home > Software engineering >  Add spaces before every repeating string in list
Add spaces before every repeating string in list

Time:03-03

I am struggling a bit with the following issue. I want to add empty spaces in front of repeating entries.

What it looks like:               What it should look like:
a                                 a
asdf                              asdf
asdf                                asdf
asdf                                asdf
b                                 b
cc                                cc
cc                                  cc
e                                 e

I tried a few things but they all tend to either add to many spaces in the follow up entries or just plain don't work.

test = ["a", "asdf", "asdf", "asdf", "b", "c", "c"]
for i in range(0, len(test)):
    temp = test[i]
    # I use a try here to avoid out of bounds exceptions
    try: 
        if test[i] == test[i   1]:        
            # checking for how many repeating entries exist after the first one 
            for j in range(1, len(test)):
                if temp == test[i   j]:
                    test[i   j] = "   "   temp
                else:
                    break
                
    except:
        pass

CodePudding user response:

The main issue here is that you are updating your array entries to have spaces in them, and then checking if they are equal to the other entries that do not have the spaces. To overcome this, you should check if they are equal with white-space removed.

You can also do this more effectively by having a spaces variable and updating it after each entry depending on whether the entry is the same as the one before or not. The following code should do what you are looking for.

test = ["a", "asdf", "asdf", "asdf", "b", "c", "c"]
spaces = 0
print(test[0]) # prints are just to show the output
for i in range(1, len(test)):
    if (test[i].lstrip() == test[i-1].lstrip()):
        spaces = 1
    else:
        spaces = 0
    test[i] = " "*spaces   test[i]
    print(test[i]) # prints are just to show the output

Output:

a
asdf
 asdf
 asdf
b
c
 c

CodePudding user response:

One way using itertools.groupby:

from itertools import groupby

res = []
for k, g in groupby(l):
    first, *rest = g
    res.extend([first, *(f"  {i}" for i in rest)])

Output:

['a', 'asdf', '  asdf', '  asdf', 'b', 'c', '  c']

Printed version:

for i in res:
    print(i)

a
asdf
  asdf
  asdf
b
c
  c

CodePudding user response:

A simple loop that corrects adjacent repeating items:

ys = [xs[0]]

for i in range(1, len(xs)):
    if xs[i] == xs[i - 1]:
        ys.append("  "   xs[i])

It's a bit more complicated if you want to alter the existing list instead:

prev = xs[0]

for i in range(1, len(xs)):
    if xs[i] == prev:
        xs[i] = "  "   xs[i]
    else:
        prev = xs[i]
  • Related