0

Its hard for me to explain this accurate, but what i want is this. The numbers between the elements containing the string '/' merged together like so:

source = ['3', '/', '7', '/', '1', '1', '/', '1', '5', '/', '2', '2', '/', '1', '1', '5']

some function....

output = ['3', '/', '7', '/', '11', '/', '15', '/', '22', '/', '115']
martineau
  • 119,623
  • 25
  • 170
  • 301

4 Answers4

1

You could try iterating through the list and keeping a tracker. When you reach a number, add it to the tracker; when you reach a /, reset and add the tracker to the list.

def merge(arr):
    ret = []
    el = ''
    for i in arr:
        if i == '/':
            ret.extend([el, '/'])
            el = ''
        else:
            el += i
    ret.append(el)
    return ret

>>> merge(['3', '/', '7', '/', '1', '1', '/', '1', '5', '/', '2', '2', '/', '1', '1', '5'])
['3', '/', '7', '/', '11', '/', '15', '/', '22', '/', '115']
rassar
  • 5,412
  • 3
  • 25
  • 41
  • Thank you for the quick response. Will spend some time to fully understand what is going on in the function, and implement it in my program. – Bertram Nyvold Sep 24 '19 at 20:55
1
def merge(source, separator):
  lst = ''.join(source).split(separator)  # join lists then split on separator
  result = [separator] * (len(lst) * 2 - 1)  # inject separator between each item
  result[0::2] = lst
  return result

source = ['3', '/', '7', '/', '1', '1', '/', '1', '5', '/', '2', '2', '/', '1', '1', '5']
print(merge(source, '/')) # ['3', '/', '7', '/', '11', '/', '15', '/', '22', '/', '115']
DarrylG
  • 16,732
  • 2
  • 17
  • 23
0

Same idea with slightly different implementation:

def func(input):
    ret = []
    i = 0
    curr_grp = []

    while i < len(input):
        if input[i] != '/':
            curr_grp.append(input[i])
        else:
            ret.append(''.join(curr_grp))
            ret.append('/')
            curr_grp = []
        i += 1

    return ret
congbaoguier
  • 985
  • 4
  • 20
0

You could use the itertools.groupby() function like this:

from itertools import groupby

separator = '/'
source = ['3', '/', '7', '/', '1', '1', '/', '1', '5', '/', '2', '2', '/', '1', '1', '5']

result = []
for blend, chars in groupby(source, lambda v: v != separator):
    result.append(''.join(chars) if blend else separator)

print(result)  # -> ['3', '/', '7', '/', '11', '/', '15', '/', '22', '/', '115']
martineau
  • 119,623
  • 25
  • 170
  • 301