个性化阅读
专注于IT技术分析

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

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

例子:

Input  : aaaaabbbbbb
Output : ab

Input : srcmini
Output : geksforgeks

Input : aabccba
Output : abcba

我们已经有解决此问题的方法, 请参阅从字符串中删除所有连续的重复项链接。我们可以使用python快速解决此问题itertools.groupby()方法。

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

groupby方法需要两个输入, 一个是可迭代的(列表, 元组, 字典)第二个是密钥功能, 它为可迭代的每个元素计算密钥。它返回键和可迭代的分组项。如果未指定键函数或为”无”, 则键默认为标识函数, 并返回不变的元素。例如,

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://docs.python.org/3/library/itertools.html

输出如下:

ab

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(1)
未经允许不得转载:srcmini » Python groupby方法删除所有连续的重复项

评论 抢沙发

评论前必须登录!