繁体   English   中英

在列表中的一系列重复元素之后添加特殊字符的最有效方法是什么?

[英]What is the most efficient way to add a special character after a sequence of repeated elements in a list?

我有一个清单:

lst= [1,1,2,2,3,3,4,4,5,5,5]

我需要准备一份这种格式的清单

lst = [1,1,$,2,2,$,3,3,$,4,4,$,5,5,5]

这是 function 我用来形成元素对并在元素对不相等时添加一个特殊字符。 当列表较小时,此方法效果很好,但当考虑较大的列表时,这不是最有效的方法。

附图

另外,有没有一种方法可以跟踪我们添加特殊字符的索引? 就像为索引值维护另一个列表一样。

IIUC,您可以使用itertools中的groupbychain

from itertools import groupby, chain
out = list(chain.from_iterable(list(g)+['$'] for _,g in groupby(lst)))[:-1]

output:

[1, 1, '$', 2, 2, '$', 3, 3, '$', 4, 4, '$', 5, 5, 5]

输入:

lst = [1,1,2,2,3,3,4,4,5,5,5]

注意。 不要使用list作为变量名,这会隐藏list python 内置

使用发电机的替代方案
def add_symbol(lst, symbol='$'):
    if lst:
        prev = lst[0]
    for item in lst:
        if item != prev:
            yield symbol
        prev = item
        yield item
            
out = list(add_symbol(lst))
将插入索引作为副作用
def add_symbol(lst, symbol='$', indices=None):
    if lst:
        prev = lst[0]
    insertions = 0
    for i, item in enumerate(lst):
        if item != prev:
            yield symbol
            if isinstance(indices, list):
                insertions += 1
                indices.append(i+insertions)
        prev = item
        yield item

idx = []
out = list(add_symbol(lst, indices=idx))

print(idx)
[3, 6, 9, 12]

print(out)
[1, 1, '$', 2, 2, '$', 3, 3, '$', 4, 4, '$', 5, 5, 5]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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