2013-11-29 64 views
1

我想用來自循環中'anotherList'的值替換原始列表中的'x-%'。 正如您所看到的,循環播放時,只保存最後一個狀態,因爲它會再次替換standardList。Python - 循環遍歷列表並在替換前保存狀態

什麼可能是'保存每個列表的狀態',然後再次循環它的最佳方式?

的結果應該是:

result = ['I', 'just', 'try','to', 'acomplish', 'this','foo', 'list'] 

我得到了這樣的:

originList = ['I', 'x-0', 'x-1','to', 'acomplish', 'x-2','foo', 'x-3'] 
anotherList = ['just','try','this','list'] 


for index in originList: 
    for num in range(0,4): 
     if 'x' in index: 
      result = str(originList).replace('x-%s'%(str(num)), anotherList[num]) 
print result 
#['I', 'x-0', 'x-1', 'to', 'acomplish', 'x-2', 'foo', 'list'] <-- wrong :X 

感謝您的幫助,因爲我不能算出它的那一刻

編輯* 如果有更清潔的解決方案,我也希望聽到

+0

你可以顯示'res'應該是什麼樣的? – aIKid

+0

啊對不起=結果 我會編輯 – xhallix

+0

感謝大家的好的解決方案和快速的幫助 – xhallix

回答

1

這裏你去!

>>> for original in originList: 
    if 'x' in original: 
     res.append(anotherList[int(original[-1])]) #grab the index 
    else: 
     res.append(original) 


>>> res 
['I', 'just', 'try', 'to', 'acomplish', 'this', 'foo', 'list'] 
>>> 

由於所需的值的指數是在originList的項目,你可以使用它,所以不需要額外的循環。希望這可以幫助!

+0

非常感謝,多數民衆贊成真棒。 我一直在尋找一個小時的解決方案。 – xhallix

+2

花費的時間越多越好:)練習使完美! – aIKid

1
originList = ['I', 'x-0', 'x-1','to', 'acomplish', 'x-2','foo', 'x-3'] 
anotherList = ['just','try','this','list'] 
res = [] 
i=0 
for index in originList: 
    if 'x' in index: 
     res.append(anotherList[i]) 
     i += 1 
    else: 
     res.append(index) 

print res 

你可以得到正確的結果! 但是,我認爲你必須使用的String.Format(像這樣)

print '{0}{1}{2}{3}'.format('a', 'b', 'c', 123) #abc123

閱讀python文檔 - string

1
originList = ['I', 'x-0', 'x-1','to', 'acomplish', 'x-2','foo', 'x-3'] 
anotherList = ['just','try','this','list'] 

def change(L1, L2): 
    res = [] 
    index = 0 
    for ele in L1: 
     if 'x-' in ele: 
      res.append(L2[index]) 
      index += 1 
     else: 
      res += [ele] 
    return res 

print(change(originList, anotherList)) 

結果:

['I', 'just', 'try', 'to', 'acomplish', 'this', 'foo', 'list'] 
2

這一個避免創建新清單

count = 0 

for word in range(0, len(originList)): 
    if 'x-' in originList[word]: 
     originList[word] = anotherList[count] 
     count += 1 

print originList 
+0

我認爲這也是一個很好的解決方案! – xhallix

+0

太棒了! – aIKid

+0

謝謝@aIKid!如果你想加入,我會打開聊天室 – samrap