Skip to content Skip to sidebar Skip to footer

Go One Step Back And One Step Forward In A Loop With Python

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 asteri

Solution 1:

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 inzip([None]*2+words, [None]+words+[None], words+[None]*2):
    if b == '*':
        print( a+c )

Solution 2:

I think you need a simple code like this:

words = ['les','engage', '*', 'ment', 'de','la']

for n,word in enumerate (words):
    if word == "*":
        exp = words[n-1] + words[n+1]
        print (exp)

Output:

"engagement"

With this output, you can subsequently check with your dictionary.

Solution 3:

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:

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

Which returns:

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

Post a Comment for "Go One Step Back And One Step Forward In A Loop With Python"