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

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]

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

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

IIUC,您可以使用 itertools:

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

输出:

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

输入:

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

注意。 NOT 使用 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]