【问题标题】:How would I detect duplicate elements of a string from another string in python?如何从python中的另一个字符串中检测字符串的重复元素?
【发布时间】:2020-02-29 08:03:41
【问题描述】:

那么我将如何使用大多数情况下的一对两行或快速修复从 python 中的另一个字符串中查找一个字符串的重复元素?

例如,

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

通过使用str2,发现str1中存在重复元素,于是检测str1中存在str2中元素的重复。不确定是否有办法通过 .count 来做到这一点,比如 str1.count(str2) 或其他东西。

我将这个上下文用于我的刽子手作业,我是一名初学者编码器,所以我们主要使用内置函数和作业的基础知识,我的循环中有一段代码将保留打印,因为它会破坏双字母。

例如。你好,研磨,调配。

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

注意:它们将被输入,所以如果有意义的话,我将无法说出或硬编码字母 c。

谢谢!

【问题讨论】:

  • 如果str2 包含更多像abccccde 这样的重复文件或者str1 中不存在像abcdez 这样的字母会怎样?
  • 也许您应该考虑使用列表或集合而不是字符串来跟踪猜测。它会让你的任务更轻松!
  • if "c" in "abccde": print('detected "c",)
  • @PartialOrder 如果我只想在列表中执行此操作,我将如何处理?
  • @Chris 检测器几乎只关心 str 1 是否与 str 2 中的任何 char 元素有任何重复,所以str1 = "abcdeffghi" str2 = "aaaaaabbbbbbcccccddeeeeefffffggghhiii" 和 str1 会告诉我字母 f

标签: python string list duplicates detection


【解决方案1】:

喏,

您基本上是在搜索两个字符串之间的差异函数。适配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

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

【讨论】:

    【解决方案2】:

    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']
    

    【讨论】:

      【解决方案3】:

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

      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 字符串中。

      【讨论】:

        猜你喜欢
        • 2018-03-13
        • 1970-01-01
        • 2017-02-21
        • 2015-10-11
        • 1970-01-01
        • 2014-03-10
        • 1970-01-01
        • 2017-03-11
        • 2019-11-11
        相关资源
        最近更新 更多