2015-05-05 27 views
2

我試圖切換列表中的字符與列表中給定位置的其他字符。例如。 ["*","*","*","*","*",.....],在[1,3,4,.....]位置 與給定的字母更改字符,例如X.在列表中切換列表中的不同數字

所以["*","*","*","*","*","*"]變得["*",X,"*",X,X,"*"]

我試過這個:

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 

但它只返回列表,["*","*","*",A,"*"]

我將如何解決這個問題?它能在課堂上更輕鬆地解決嗎?那樣的話,這個班怎麼樣?

+1

接受一個答案......看到這個http://meta.stackexchange.com/questions/ 5234/how-does-accepting-an-answer-work/5235#5235 –

回答

4

您可以使用enumerate列表理解中:

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

非常感謝!很有幫助! – Karl

2
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") 

打印

['', '', '', '', '', '', ''] 
['', 'x', '', 'x', '', 'x', ''] 
+0

非常感謝!很有幫助! – Karl

+0

@Karl我很感謝謝謝,但您應該選擇一個答案並將其標爲已接受。如果我是誠實的,我認爲你應該去卡斯拉的答案。 – EvenLisle

+0

對不起,我不是一個普通的訪問者,也不知道事情如何完成! – Karl