【问题标题】:Removing only alpha duplicates仅删除 alpha 重复项
【发布时间】:2013-05-15 08:30:49
【问题描述】:

在 Python 中,我想从字符串中删除重复的字母,而不是数字或空格。我想出了:

result = []
seen = set()
for char in string:
    if char not in seen:
        seen.add(char)
        result.append(char)
return "".join(result)

但这使得:

>>> delete_duplicate_letters("13 men were wounded in an explosion yesterday around 3:00pm.")
13 menwroudiaxplsyt:0.

当我想要时:

>>> delete_duplicate_letters("13 men were wounded in an explosion yesterday around 3:00pm.")
13 men wr oud i a xpls yt 3:00.

我尝试使用letter 代替charisalpha() 函数和if int 语句等,但我什么都做不了。

【问题讨论】:

    标签: python python-2.7 duplicate-removal alphanumeric


    【解决方案1】:
    >>> from string import digits, whitespace
    >>> from collections import OrderedDict
    >>> s = set(whitespace + digits)
    >>> ''.join(OrderedDict((object() if c in s else c, c) for c in text).values())
    '12 men wr oud i a xpls yt  3:00.'
    

    object() 此处仅用于确保您要离开的字符的键始终是唯一的,因为object() 每次都会创建不同的对象。其他字符本身用作键,因此过滤掉重复项。

    【讨论】:

    • 这值得一票。看起来……太棒了
    【解决方案2】:

    试试这个:

    result = ""
    for char in string:
        if not (char.isalpha() and char in result):
            result += char
    

    【讨论】:

    • +1 是一个不错的简单解决方案,只是希望字符串不会变得非常大,否则二次运行时会开始
    【解决方案3】:

    使用str.isspacestr.isdigit

    strs = "13 men were wounded in an explosion yesterday around 3:00pm."
    result = []
    seen = set()
    for char in strs:
        if char not in seen:
            if not (char.isspace() or char.isdigit()):
               seen.add(char)
            result.append(char)
    print "".join(result)
    

    输出:

    13 men wr oud i a xpls yt  3:00.
    

    【讨论】:

      【解决方案4】:

      看来你快到了。您可以在循环中添加一些检查:

      result = []
      seen = set()
      for char in string:
          if char.isdigit() or char.isspace():
              result.append(char)
          elif char not in seen:
              seen.add(char)
              result.append(char)
      return "".join(result)
      

      【讨论】:

      • +1 很好的解决方案,但这会产生额外的空间,因为around 已完全删除
      • @NiklasHansson 查看 OP 的更新:应保留多个数字。
      • 我的错,他改变了他的榜样。
      猜你喜欢
      • 2021-07-16
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      相关资源
      最近更新 更多