[英]What is the most efficient way to add a special character after a sequence of repeated elements in a list?
I have a list:我有一个清单:
lst= [1,1,2,2,3,3,4,4,5,5,5]
I need to prepare a list in this format我需要准备一份这种格式的清单
lst = [1,1,$,2,2,$,3,3,$,4,4,$,5,5,5]
This is the function I have used to form pairs of elements and add a special character when the pairs are not equal.这是 function 我用来形成元素对并在元素对不相等时添加一个特殊字符。 This approach works well when the list size is small, but when bigger lists are considered, this is not the most efficient way.
当列表较小时,此方法效果很好,但当考虑较大的列表时,这不是最有效的方法。
Also, is there a way where we can keep a track of the indices we are adding the special character at?另外,有没有一种方法可以跟踪我们添加特殊字符的索引? Like maintaining another list just for the index values.
就像为索引值维护另一个列表一样。
IIUC, you can use groupby
and chain
from itertools
: IIUC,您可以使用
itertools
中的groupby
和chain
:
from itertools import groupby, chain
out = list(chain.from_iterable(list(g)+['$'] for _,g in groupby(lst)))[:-1]
output: output:
[1, 1, '$', 2, 2, '$', 3, 3, '$', 4, 4, '$', 5, 5, 5]
input:输入:
lst = [1,1,2,2,3,3,4,4,5,5,5]
NB.注意。 do NOT use
list
as variable name, this shadows the list
python builtin不要使用
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.