【问题标题】:Merging consecutive elements recursively in a list of strings in Python在Python中的字符串列表中递归合并连续元素
【发布时间】:2020-09-28 21:28:21
【问题描述】:

我有一个字符串列表,需要转换成一个较小的字符串列表,这取决于两个连续的元素是否属于同一个短语。 目前,如果i-th 字符串的最后一个字符较低且i+1-th 字符串的第一个字符也较低,则会发生这种情况,但将来应检查更复杂的条件。

比如这个很深奥的文字:

['I am a boy',
'and like to play'
'My friends also'
'like to play'
'Cats and dogs are '
'nice pets, and'
'we like to play with them'
]

应该变成:

['I am a boy and like to play', 
 'My friends also like to play',
 'Cats and dogs are nice pets, and we like to play with them'
]

我的python解决方案

【问题讨论】:

    标签: python string recursion


    【解决方案1】:

    既然你想递归地做,你可以试试这样:

    def join_text(text, new_text):
        if not text:
            return
        if not new_text:
            new_text.append(text.pop(0))
            return join_text(text, new_text)
        phrase = text.pop(0)
        if phrase[0].islower():  # you can add more complicated logic here
            new_text[-1] += ' ' + phrase
        else:
            new_text.append(phrase)
        return join_text(text, new_text)
    
    
    phrases = [
        'I am a boy',
        'and like to play',
        'My friends also',
        'like to play',
        'Cats and dogs are ',
        'nice pets, and',
        'we like to play with them'
    ]
    
    
    joined_phrases = []
    join_text(phrases, joined_phrases)
    print(joined_phrases)
    

    我的解决方案在 witespaces 方面存在一些问题,但我希望你明白这一点。 希望对您有所帮助!

    【讨论】:

    • 简单的条带可以帮助解决这个问题。
    【解决方案2】:

    这是你的代码检查它

    data = ['I am a boy',
    'and like to play'
    'My friends also'
    'like to play'
    'Cats and dogs are '
    'nice pets, and'
    'we like to play with them'
    ]
    
    joined_string = ",".join(data).replace(',',' ')
    
    import re
    values = re.findall('[A-Z][^A-Z]*', joined_string)
    print(values)
    

    【讨论】:

      【解决方案3】:

      我认为您发布的数据是逗号分隔的。如果是 pfb 一个简单的循环解决方案。

      data=['I am a boy',
      'and like to play',
      'My friends also',
      'like to play',
      'Cats and dogs are ',
      'nice pets, and',
      'we like to play with them'
      ]
      
      required_list=[]
      
      for j,i in enumerate(data):
          print(i,j)
          if j==0:
              req=i
          else:
              if i[0].isupper():
                  required_list.append(req)
                  req=i
              else:
                  req=req+" "+i
      required_list.append(req)
      
      
      print(required_list)    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2021-12-05
        • 2021-04-07
        相关资源
        最近更新 更多