如何在 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 的数字。