Python - 从字符串中去除重复项
def remove_duplicates(strng):
"""
Returns a string which is the same as the argument except only the
first occurrence of each letter is present. Upper and lower case
letters are treated as different. Only duplicate letters are removed,
other characters such as spaces or numbers are not changed.
>>> remove_duplicates('apple')
'aple'
>>> remove_duplicates('Mississippi')
'Misp'
>>> remove_duplicates('The quick brown fox jumps over the lazy dog')
'The quick brown fx jmps v t lazy dg'
>>> remove_duplicates('121 balloons 2 u')
'121 balons 2 u'
"""
s = strng.split()
return strng.replace(s[0],"")
我在写一个函数,用来去掉重复的字母,但到现在为止已经折腾了一个小时,还是没搞定。希望能得到一些帮助,谢谢。
3 个回答
0
试试这个...
def remove_duplicates(s):
result = ""
dic = {}
for i in s:
if i not in dic:
result+=i
if ord(i.lower()) >= ord('a') and ord(i.lower()) <= ord('z'):
dic[i] = 1
return result
2
使用列表推导式:
>>> from string import whitespace, digits
>>> s = 'The quick brown fox jumps over the lazy dog'
>>> ''.join([c for i, c in enumerate(s) if c in whitespace+digits \
or not c in s[:i]])
3
这不是最有效的方法,但却是最简单明了的做法:
>>> s = 'The quick brown fox jumps over the lazy dog'
>>> import string
>>> n = ''
>>> for i in s:
if i not in string.ascii_letters:
n += i
elif i not in n:
n += i
>>> n
'The quick brown fx jmps v t lazy dg'