当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Find an item in list and change the next item in list as 'RD_PUNC'

问题描述:

My code is:

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']

I want to find 2.,4., any number followed by a'.' and change the next item in list as 'RD_PUNC'.

my desired output is:

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

网友答案:

Using 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

Output:

['1.alen', 'N_NN', '2.', 'RD_PUNC', '3.abr', 'N_NNP', '4.london', 'N_NST', '5.', 'RD_PUNC']
分享给朋友:
您可能感兴趣的文章:
随机阅读: