【问题标题】:How to group consecutive letters in a string in Python?如何在 Python 中对字符串中的连续字母进行分组?
【发布时间】:2021-02-24 17:52:05
【问题描述】:

例如:string = aaaacccc,那么我需要输出为4a4c。有没有办法在不使用任何高级方法(例如库或函数)的情况下做到这一点?

另外,如果有人知道如何反其道而行之:将“4a4c: 变为 aaaacccc”,那就太好了。

【问题讨论】:

  • 你尝试了什么?你遇到了什么问题?
  • 到目前为止,我所做的只是确保字符串只包含字母:if string.isalpha() == true:

标签: python string compression


【解决方案1】:

这将在一次迭代中完成工作

保留两个临时变量,一个用于当前字符,另一个用于该字符的计数,一个用于结果。

只需遍历字符串,如果与前一个匹配,则继续增加计数。

如果没有,则使用字符的计数和值更新结果并更新字符和计数。

最后将最后一个字符和计数添加到结果中。完成!

input_str = "aaaacccc"
if input_str.isalpha():
  current_str = input_str[0]
  count = 0
  final_string = ""
  for i in input_str:
    if i==current_str:
      count+=1
    else:
      final_string+=str(count)+current_str
      current_str = i
      count = 1
  final_string+=str(count)+current_str

  print (final_string)

【讨论】:

    【解决方案2】:

    另一个解决方案,我什至包括您在帖子中提到的拼凑反向操作。两者都在 O(n) 中运行并且相当容易理解。编码与 Akanasha 发布的基本相同,在我编写 decode() 时,他发布答案的速度更快。

    def encode(x):
        if not x.isalpha():
            raise ValueError()
        output = ""
        current_l = x[0]
        counter = 0
        for pos in x:
            if current_l != pos:
                output += str(counter) + current_l
                counter = 1
                current_l = pos
            else:
                counter += 1
    
        return output + str(counter) + current_l
    
    
    def decode(x):
        output = ""
        i = 0
        while i < len(x):
            if x[i].isnumeric():
                n = i + 1
                while x[n].isnumeric():
                    n += 1
                output += int(x[i:n])*x[n]
                i = n
            i += 1
        return output
    
    
    test = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasasggggggbbbbdd"
    test1 = encode(test)
    print(test1)
    
    test2 = decode(test1)
    print(test2)
    
    print(test == test2)
    

    【讨论】:

      【解决方案3】:

      是的,您不需要任何库:

      list1 = list("aaaacccc")
      letters = []
      for i in list1:
          if i not in letters:
              letters.append(i)
      string = ""
      for i in letters:
          string += str(list1.count(i))
          string+=str(i)
      print(string)
      

      基本上,它遍历列表,找到唯一的字母,然后用字母本身打印计数。反转将是相同的功能,只需打印金额即可。

      【讨论】:

      • 你能让它在 O(n) 而不是 O(n^2) 中运行吗?
      • @DeepSpace 这不是 O(n^2) 它是 O(2n)
      • @Akansha 不,更糟糕的情况是 O(n^2),因为 list.count 是 O(n)
      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 2011-08-19
      相关资源
      最近更新 更多