[英]How to merge elements together in a list that are separated by ' / ' on both sides?
我很難准確地解釋這一點,但我想要的是這個。 包含字符串 '/' 的元素之間的數字合並在一起,如下所示:
source = ['3', '/', '7', '/', '1', '1', '/', '1', '5', '/', '2', '2', '/', '1', '1', '5']
一些 function....
output = ['3', '/', '7', '/', '11', '/', '15', '/', '22', '/', '115']
您可以嘗試遍歷列表並保留跟蹤器。 當您到達一個號碼時,將其添加到跟蹤器; 當您到達 / 時,重置並將跟蹤器添加到列表中。
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']
相同的想法,實現略有不同:
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
您可以像這樣使用itertools.groupby()
function:
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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.