Karl
Karl

Reputation: 143

Switching characters in a list for different numbers in a list

I'm trying to switch out characters in a list for other characters with a given position in that list. For ex. ["*","*","*","*","*",.....], change the characters in position [1,3,4,.....] with a given letter, for example X.

So ["*","*","*","*","*","*"] becomes ["*",X,"*",X,X,"*"].

I've tried with this:

def test():
letter="a"
secret="*****"
secret2=list(secret)
pos=[1,3]
y = 1
x = pos[y]
flag = 0
while flag < 2:
    secret2[x]=letter
    flag = (flag + 1)
    y = (y+1)
return secret2

But it only returns the list as ["*","*","*",A,"*"]

How would i solve this? Would it be able to solve easier with a class? In that case, how would this class look like?

Upvotes: 2

Views: 55

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

You can use enumerate within a list comprehension :

>>> l=[1,3,6]
>>> li=["*","*","*","*","*",'*','*']
>>> ['X' if i in l else j for i,j in enumerate(li)]
['*', 'X', '*', 'X', '*', '*', 'X']

Upvotes: 4

EvenLisle
EvenLisle

Reputation: 4812

def substitute_at_positions(lst, positions, substitute):
  return [substitute if i in positions else lst[i] for i in xrange(len(lst))]

lst = ["","","","","","",""]
print lst
print substitute_at_positions(lst, {1,3,5}, "x")

prints

['', '', '', '', '', '', '']
['', 'x', '', 'x', '', 'x', '']

Upvotes: 2

Related Questions