我想用來自循環中'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
感謝您的幫助,因爲我不能算出它的那一刻
編輯* 如果有更清潔的解決方案,我也希望聽到
你可以顯示'res'應該是什麼樣的? – aIKid
啊對不起=結果 我會編輯 – xhallix
感謝大家的好的解決方案和快速的幫助 – xhallix