如何在python3中找到字符串中的重复项?

2024-10-03 11:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是找到字符串中的重复字符,用其他值替换那些唯一和非唯一的元素,并将这些其他值放在另一个字符串中。你知道吗

我用了Counter,但到目前为止我得到的是:

from collections import Counter

def duplicate_encode(word):
    word = word
    final_result = ""
    dict_input = Counter(word)
    print(dict_input)
    print(dict_input.items())
    for key in dict_input:
        x = int(dict_input[key])
        print("this is key" + "\t" + key)
        print(x)
        if x == 1:
            final_result += "("
        elif x != 1:
            final_result += ")"
    print("'" + final_result + "'")

duplicate_encode("binaryy")

输出:

'((((()'

例如,对于"binaryy",输出应该是'((((())',而不是'((((()'。你知道吗

另外,有没有比print("'" + final_result + "'")更好的打印字符串的方法


Tags: key字符串元素目标inputcounterresult字符
2条回答

在您最初的方法中,当您执行for key in dict_input:操作时,您正在迭代计数器的键,因此您将最终创建一个等于计数器中键长度的字符串,正如您在输出中观察到的((((()。你知道吗

此外,字典仅来自Python3.6+,因此您无论如何都不能遍历键,这些键可以无序地重新创建原始字符串。你知道吗

相反,一旦创建了计数器,就需要遍历每个字符,并根据该字符的计数是1还是更大,将()添加到字符串中

同样对于带引号的打印,可以使用f字符串或字符串格式返回带引号的输出

from collections import Counter

def duplicate_encode(word):

    counter = Counter(word)

    #Add ( if the count of character is 1, else add )
    output = ''.join('(' if counter.get(c) == 1 else ')' for c in word)

    #Return a f-string with single quotes around it
    return f"'{output}'"

    #Or use string formatting
    #return "'{}'".format(output)

print(duplicate_encode("binaryy"))

输出将是

'((((())'

循环不应超过for key in dict_input:。这只适用于您的示例,因为A)字典是在python3.6+中排序的,B)您只有一个重复范围。循环应该对字符串中的实际字符进行编码:

final_result = ''
for c in word:
    final_result += '(' if dict_input[c] == 1 else ')'

你可以(也许应该)缩短到

final_result = ''.join('(' if dict_input[c] == 1 else ')' for c in word)

要打印带引号的字符串,只需使用repr。或者直接:

print(repr(final_result))

或使用格式:

print(f'{final_result!r}')

相关问题 更多 >