X.Z
X.Z

Reputation: 1128

how to change one element's value base on its previous one in a loop

In Python 3, how do I change the element between 'b' into Capitalize form. from ls = ['a','b','c','d','b','f'] to ls = ['a','b','C','D','b','f']

is there a way to control the position of iterator?

Upvotes: 0

Views: 41

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 113915

Personally, I would go with the slicing syntax that has already been suggested. But here's another solution, in case you're interested (same runtime complexity, better space complexity):

>>> ls = ['a','b','c','d','b','f']
>>> mode = False
>>> for i,char in enumerate(ls):
...     if char == 'b':
...         mode = not mode
...         continue
...     if mode:
...         ls[i] = char.upper()
... 
>>> ls
['a', 'b', 'C', 'D', 'b', 'f']

Upvotes: 0

falsetru
falsetru

Reputation: 368964

Using slice:

>>> ls = ['a','b','c','d','b','f']
>>> i = ls.index('b')
>>> j = ls.index('b', i+1)
>>> ls[i+1:j] = map(str.upper, ls[i+1:j])
>>> ls
['a', 'b', 'C', 'D', 'b', 'f']

Upvotes: 1

Related Questions