如何从python这样的列表中删除连续的重复项?
lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
拥有唯一的列表或集合并不能解决问题,因为在先前的列表中有一些重复的值,例如1,...,1。
我希望结果是这样的:
newlst = [1,2,4,1,3,5]
当我有一个这样的列表[4, 4, 4, 4, 2, 2, 3, 3, 3, 3, 3, 3]
并且我希望结果是[4,2,3,3]
而不是时,也请考虑一下这种情况[4,2,3]
。
itertools.groupby()是您的解决方案。
newlst = [k for k, g in itertools.groupby(lst)]
如果您希望通过项的值对分组大小进行分组和限制分组大小,这意味着8 4将是[4,4],而9 3将是[3,3,3],这里有2个选项可以做到这一点:
import itertools
def special_groupby(iterable):
last_element = 0
count = 0
state = False
def key_func(x):
nonlocal last_element
nonlocal count
nonlocal state
if last_element != x or x >= count:
last_element = x
count = 1
state = not state
else:
count += 1
return state
return [next(g) for k, g in itertools.groupby(iterable, key=key_func)]
special_groupby(lst)
或者
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
newlst = list(itertools.chain.from_iterable(next(zip(*grouper(g, k))) for k, g in itertools.groupby(lst)))
选择您认为合适的任何一种。两种方法都适用于数字> 0。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句