【问题标题】:How can I remove duplicate string with Python?如何使用 Python 删除重复的字符串?
【发布时间】:2021-04-16 07:00:23
【问题描述】:

我要学python,有问题要处理 下面的例子:

string1 = "Galaxy S S10 Lite"
string2 = "Galaxy Note Note 10 Plus"

如何删除后两个重复的“S”和“S”或“Note”和“Note”?

结果应该是这样的

string1a = "Galaxy S10 Lite"
string2a = "Galaxy Note 10 Plus"

如何只删除第二个重复项而不改变单词的顺序!

【问题讨论】:

  • 我会使用拆分并删除数组的第二个位置。
  • @Capie 我认为不能保证这个词总是排在第二位。
  • “S”和“S10”不是同一个词。没有神奇的功能可以假设并做你想做的事。
  • @AKX 不要假设这么快,让作者来回答。在我看来,他得到了 2 个字符串,其中第一个字符串是前 2 个项目,第二个字符串是最后 2 个项目。
  • 结构总是像 string1 或 string2,我只想删除第二和第三位置的 1 2 个连续相同的单词,输出看起来像 string1a 或 string2a

标签: python string duplicates


【解决方案1】:
string1a = string1.split()
del string1a[1]
string1a = " ".join(string1a)

这可以满足您对提供的 2 个字符串的要求。 如果您确定字符串的第二个和第三个单词是重复的,它只会在您想要的所有字符串中工作,优先考虑第三个。

【讨论】:

    【解决方案2】:

    接受的答案仅手动删除句子中的第二个单词。 如果你有一个很长的字符串,清理起来会很乏味。

    我假设只有两种情况:

    1. 如果它与以下单词的第一个字母相同,则跳过该字母
    2. 如果与下一个单词相同,则跳过该单词

    此功能可以自动清理它们

    def clean_string(string):
        """Clean if there were sequentially duplicated word or letter"""
        following_word = ''
        complete_words = []
        # loop through the string in reverse to be able to skip the earlier word/letter
        # string.split() splits your string by each space and make it as a list
        for word in reversed(string.split()):
            # to skip duplicated letter, in your case is to skip "S" and retain "S10"
            if (len(word) == 1) and (following_word[0] == word):
                following_word = word
                continue
            # to skip duplicated word, in your case is to skip "Note" and retain latter "Note"
            elif word == following_word:
                following_word = word
                continue
            following_word = word
            complete_words.append(word)
        # join all appended word and re-reverse it to be the expected sequence
        return ' '.join(reversed(complete_words))
    

    【讨论】:

      猜你喜欢
      • 2011-12-09
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 2021-06-05
      相关资源
      最近更新 更多