Python - 如何仅在字符串中连续删除重复项?

use*_*020 14 python string duplicates

对于一个字符串,例如'12233322155552',通过删除重复项,我可以得到'1235'.

但我想保留的是'1232152',只删除连续的重复项.

cyb*_*ron 10

微软/亚马逊求职面试的问题类型:这是伪代码,实际代码留作练习.

for each char in the string do:
   if the current char is equal to the next char:
      delete next char
   else
     continue

return string
Run Code Online (Sandbox Code Playgroud)

作为更高级别,尝试(实际上不是实现):

for s in string:
  if s == s+1:  ## check until the end of the string
     delete s+1
Run Code Online (Sandbox Code Playgroud)

  • 很好的调用没有给出确切的代码(虽然Python已经非常接近伪代码). (4认同)

aka*_*iya 10

你可以使用itertools,这里是一个班轮

>>> s = '12233322155552'
>>> ''.join(i for i, _ in itertools.groupby(s))
'1232152'
Run Code Online (Sandbox Code Playgroud)


Pau*_*tas 9

import re

# Only repeated numbers
answer = re.sub(r'(\d)\1+', r'\1', '12233322155552')

# Any repeated character
answer = re.sub(r'(.)\1+', r'\1', '12233322155552')
Run Code Online (Sandbox Code Playgroud)

  • 使用 `r'(.)\1+'` 将此解决方案推广到任何重复字符,并使用 `r'(\S)\1+'` 推广到任何*非空白*字符。 (2认同)

DSM*_*DSM 7

提示:itertools模块非常有用.一个函数,特别是itertools.groupby,可能在这里非常方便:

itertools.groupby(iterable [,key])

创建一个从迭代中返回连续键和组的迭代器.关键是计算每个元素的键值的函数.如果未指定或为None,则键默认为标识函数并返回元素不变.通常,可迭代需要已经在相同的键函数上排序.

因此,由于字符串是可迭代的,您可以做的是:

use groupby to collect neighbouring elements
extract the keys from the iterator returned by groupby
join the keys together
Run Code Online (Sandbox Code Playgroud)

这一切都可以在一条简洁的线上完成..