使用嵌套的while循环删除字符串中的重复项

时间:2019-06-17 17:26:10

标签: python-3.x

我正在尝试使用经典的嵌套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

2 个答案:

答案 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')))

测试:https://ideone.com/8lCPec

但是,如果您明确希望对代码进行修复(以及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)必须在外循环内重新设置
  • 删除字符时,必须再次检查其位置,因此索引不会增加。