📜  Python groupby 方法删除所有连续重复

📅  最后修改于: 2022-05-13 01:55:16.696000             🧑  作者: Mango

Python groupby 方法删除所有连续重复

给定一个字符串S,删除所有连续的重复项。

例子:

Input  : aaaaabbbbbb
Output : ab

Input : geeksforgeeks
Output : geksforgeks

Input : aabccba
Output : abcba

我们有针对此问题的现有解决方案,请参阅从字符串链接中删除所有连续重复项。我们可以使用 itertools.groupby() 方法在Python中快速解决这个问题。

itertools.groupby(iterable,key[optional]) 如何在Python中工作?

按方法分组需要两个输入,一个是可迭代的(列表、元组、字典) ,第二个是键函数,它计算可迭代中存在的每个元素的键。它返回分组项的键和可迭代项。如果未指定 key函数或为 None,则 key 默认为标识函数并返回未更改的元素。例如,

numbers = [1, 1, 1, 3, 3, 2, 2, 2, 1, 1]
import itertools
for (key,group) in itertools.groupby(numbers):
    print (key,list(group))

输出:

(1, [1, 1, 1])
(3, [3, 3])
(2, [2, 2])
(1, [1, 1])
# function to remove all consecutive duplicates 
# from the string in Python
  
from itertools import groupby
def removeAllConsecutive(input):
    
     # group all consecutive characters based on their 
     # order in string and we are only concerned
     # about first character of each consecutive substring
     # in given string, so key value will work for us
     # and we will join these keys without space to 
     # generate resultant string
     result = []
     for (key,group) in groupby(input):
          result.append(key)
  
     print (''.join(result))
       
# Driver program
if __name__ == "__main__":
    input = 'aaaaabbbbbb'
    removeAllConsecutive(input)

参考 :
https://文档。 Python.org/3/library/itertools.html

输出:

ab