1

在 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而不是函数和语句等char,但我无法得到任何工作。isalpha()if int

4

4 回答 4

2
>>> 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()每次都会创建一个不同的对象。其他字符本身用作键,因此会过滤重复项。

于 2013-05-15T08:49:36.300 回答
1

尝试这个:

result = ""
for char in string:
    if not (char.isalpha() and char in result):
        result += char
于 2013-05-15T08:36:05.407 回答
1

使用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.
于 2013-05-15T08:36:17.887 回答
0

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

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)
于 2013-05-15T08:37:28.377 回答