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

前端 未结 3 1443
天命终不由人
天命终不由人 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 17:51

    Instead of thinking "time travel" (i.e. go back and forth), the Pythonic way would be to think functional (time travel has it's place in very resource constrained environments).

    One way is to go the enumeration way as @Yosufsn showed. Another is to zip the list with itself, but with padding appended on either side. Like this:

    words = ['les','engage', '*', 'ment', 'de','la'] 
    for a,b,c in zip([None]*2+words, [None]+words+[None], words+[None]*2):
        if b == '*':
            print( a+c )
    

提交回复
热议问题