go one step back and one step forward in a loop with python

前端 未结 3 1441
天命终不由人
天命终不由人 2021-01-23 17:18

I need to loop in a list containing french words and find an asterisk because I want to concatenate the word before the asterisk and the word after the asterisk each time an ast

3条回答
  •  心在旅途
    2021-01-23 18:01

    I wondered how to manage a list (nonsense) like this:

    words = ['Bien', '*', 'venue', 'pour', 'les','engage', '*', 'ment', 'trop', 'de', 'YIELD', 'peut','être','contre', '*', 'productif' ]
    

    So I came u with a method like this:

    def join_asterisk(ary):
      i, size = 0, len(ary)
      while i < size-2:
        if ary[i+1] == '*':
          yield ary[i] + ary[i+2]
          i+=2
        else: yield ary[i]
        i += 1
      if i < size:
        yield ary[i]
    

    Which returns:

    print(list(join_asterisk(words)))
    #=> ['Bienvenue', 'pour', 'les', 'engagement', 'trop', 'de', 'YIELD', 'peut', 'être', 'contreproductif']
    

提交回复
热议问题