2014-01-30 43 views
0

我的代碼是:查找列表中的項目,並在列表中更改的下一個項目爲「RD_PUNC」

for i in range(0,len(mylist1)):  

     dot=str(i)+'.' 
     print dot , mylist1[i] 
     if dot in mylist1: 
      print "find" 
      mylist1[i+1]='RD_PUNC' 
mylist1=['1.alen','N_NN','2.','N_NP','3.abr','N_NNP','4.london','N_NST','5.','N_NNP'] 

我想找到2,4,隨後是任何數量的「」並將列表中的下一個項目更改爲'RD_PUNC'。
我的期望的輸出是:

mylist1=['1.alen','N_NN','2.','RD_PUNC','3.abr','N_NNP','4.london','N_NST','5.','RD_PUNC'] 

回答

1

使用itertools:

from itertools import izip 
import re 
mylist1=['1.alen','N_NN','2.','RD_PUNC','3.abr','N_NNP','4.london','N_NST','5.','RD_PUNC'] 
newList = [] 
def pairwise(iterable): 
    a = iter(iterable) 
    return izip(a, a) 

replaceX = False 
for x, y in pairwise(mylist1): 
    if replaceX: 
     x = 'RD_PUNC' 
     replaceX = False 
    elif re.match(r'\d+\.$', x): 
     y = 'RD_PUNC' 
    if re.match(r'\d+\.$', y): 
     replaceX = True 
    newList.append(x) 
    newList.append(y) 

print newList 

輸出:

['1.alen', 'N_NN', '2.', 'RD_PUNC', '3.abr', 'N_NNP', '4.london', 'N_NST', '5.', 'RD_PUNC']