说我有一个这样的字符串列表
stringlist = ['this', 'is', 'a', 'str', '##ing', 'list', 'for', 'ex', '##ample', 'for']
我想合并以“##”开头的元素之前和之上的元素,并删除“##”。
所以'str'和'##ing'将被合并到'string','ex'和'##ample'将被合并到'example'。
所以这将是想要的结果
['this', 'is', 'a', 'string', 'list', 'for', 'example', 'for']
我写了一个 for 循环来解决这个问题
new = []
for idx, ele in enumerate(stringlist):
if ele.startswith('##'):
new[-1] = new[-1] + ele[2:]
else:
new.append(ele)
是否有计算效率更高或编程更优雅的方法来获得此结果?
这是一个替代解决方案,它成对地遍历列表,如果添加到列表中的最后一项是通过加入对而形成的字符串,则跳过一对。我不知道它会比您现有的解决方案更有效,但它的好处是它不需要修改已添加到新列表中的项目。
def merge(stringlist):
new = []
skip = False
for first, second in zip(stringlist, (stringlist[1:] + ['#'])):
if skip:
skip = False
elif second.startswith('#'):
new.append(f'{first}{second.lstrip("#")}')
skip = True
else:
new.append(first)
return new
['#']
必须添加到stringlist[1:]
以补偿zip
一旦最短的迭代用完就终止的事实。请注意,您也可以使用itertools.zip_longest
输出:
>>> merge(['this', 'is', 'a', 'str', '##ing', 'list', 'for', 'ex', '##ample', 'for', '##a'])
['this', 'is', 'a', 'string', 'list', 'for', 'example', 'fora']
>>> merge(['this', 'is', 'a', 'str', '##ing', 'list', 'for', 'ex', '##ample', 'for'])
['this', 'is', 'a', 'string', 'list', 'for', 'example', 'for']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句