我如何从python中的另一个字符串中检测出一个字符串的重复元素?

问题描述 投票:0回答:3

因此,我将如何使用大部分情况下的一到两行或快速解决方案,从python中的另一个字符串中找到一个字符串的重复元素?

例如,

str1 = "abccde"
str2 = "abcde"
# gets me c

通过使用str2,发现str1中存在重复的元素,因此检测到str1在str2中具有元素的重复。不知道是否有一种方法可以通过.count来做到这一点,例如str1.count(str2)之类的东西。

我正在将上下文用于我的子手任务,并且我是一个初学者,所以我们主要使用内置函数和这些任务的基础知识,我的循环中有一部分代码可以继续打印因为它会带两个字母。

例如你好,研磨,混合。

所以我几乎做了一个“用过的”字符串,并且我试图将其与我的正确字母列表进行比较,并且猜测被“附加”了,所以我可以避免这种情况。

注意:它们将被输入,因此如果可行,我将无法说出或仅对字母c进行硬编码。

谢谢!

python string list duplicates detection
3个回答
0
投票

Ciao,

您基本上是在两个字符串之间搜索diff函数。适应this beautiful answer

import difflib

cases=[('abcccde', 'abcde')] 

for a,b in cases:     
    print('{} => {}'.format(a,b))  
    for i,s in enumerate(difflib.ndiff(a, b)):
        if s[0]==' ': continue
        elif s[0]=='-':
            print(u'The second string is missing the "{}" in position {} of the first string'.format(s[-1],i))
        elif s[0]=='+':
            print(u'The first string is missing the "{}" in position {} of the second string'.format(s[-1],i))    
    print() 

输出

abcccde => abcde
The second string is missing the "c" in position 3 of the first string
The second string is missing the "c" in position 4 of the first string

希望它会有所帮助,并祝您有美好的一天,安东尼诺


0
投票

setstr.count一起使用:

def find_dup(str1, str2):
    return [i for i in set(str1) if str1.count(i) > 1 and i in set(str2)]

输出:

find_dup("abccde", "abcde")
# ['c']
find_dup("abcdeffghi" , "aaaaaabbbbbbcccccddeeeeefffffggghhiii") # from comment
# ['f']

0
投票

我的猜测是,也许您正在尝试编写类似于以下内容的方法:

def duplicate_string(str1: str, str2: str) -> str:
    str2_set = set(str2)
    if len(str2_set) != len(str2):
        raise ValueError(f'{str2} has duplicate!')

    output = ''
    for char in str1:
        if char in str2_set:
            str2_set.remove(char)
        else:
            output += char

    return output


str1 = "abccccde"
str2 = "abcde"

print(duplicate_string(str1, str2))

输出

ccc

[这里,如果str2本身有重复项,我们将首先提出一个错误。然后,我们遍历str1,或者从str1_set中删除一个字符,或者将重复项追加到output字符串中。

© www.soinside.com 2019 - 2024. All rights reserved.