我正在尝试使用经典的嵌套while循环来删除重复项,但是如果字符串中间(而不是第一个和最后一个索引中)存在两个相同的字符,那么它就不会删除重复项。 / p>
def removeduplicates(String):
result = ''
list_of_char = []
for i in String:
list_of_char.append(i)
k = 1
l = 1
a = 0
b = 1
print(len(list_of_char))
while k < len(list_of_char):
while l < len(list_of_char):
if list_of_char[a].lower() == list_of_char[b].lower():
del list_of_char[b]
else:
pass
b = b + 1
l = l + 1
k = k + 1
for j in list_of_char:
result = result + j
return result
print(removeduplicates('Arpitr'))
预期:Arpit
答案 0 :(得分:0)
您可以这样做:
def removeduplicates(string):
output = ""
for x in string:
if x not in output:
output += x
return output
print(removeduplicates('Arpitr'))
输出
'Arpit'
答案 1 :(得分:0)
OrderedDict
可以执行以下操作:
import collections
print(''.join(collections.OrderedDict.fromkeys('Arpitr')))
但是,如果您明确希望对代码进行修复(以及lower()
),
def removeduplicates(String):
result = ''
list_of_char = []
for i in String:
list_of_char.append(i)
k = 0
print(len(list_of_char))
while k < len(list_of_char)-1:
l = k + 1
while l < len(list_of_char):
if list_of_char[k].lower() == list_of_char[l].lower():
del list_of_char[l]
else:
l = l + 1
k = k + 1
for j in list_of_char:
result = result + j
return result
print(removeduplicates('Arpraprapiiiiraptr'))
在这里测试:https://ideone.com/BxGBhR
两件事:
l
(或者也许是b
)必须在外循环内重新设置