简体   繁体   中英

How to merge elements together in a list that are separated by ' / ' on both sides?

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']

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']
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']

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

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM