如何修改在一个术语列表中特定术语后面的所有术语?

2024-05-28 22:57:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张这样的字表:

 list = ['I', 'did', 'not', 'enjoy', 'the', 'movie']

所以,目的是,如果单词“not”出现在单词列表中,那么下面的所有单词都应该在左边加上一个“not”。例如,上面列表的输出应该是:

output_list = ['I', 'did', 'not', 'NOT_enjoy', 'NOT_the', 'NOT_movie']

Tags: the目的列表outputnotmovie单词list
3条回答

此程序似乎按您的要求执行:

def main():
    array = ['I', 'did', 'not', 'enjoy', 'the', 'movie']
    output_array = modify(array)
    print(output_array)

def modify(array):
    iterator, output_array = iter(array), []
    for word in iterator:
        output_array.append(word)
        if word.upper() == 'NOT':
            break
    for word in iterator:
        output_array.append('NOT_' + word)
    return output_array

if __name__ == '__main__':
    main()

您可以查看上的same program的输出Ideone.com公司. 你知道吗

如果您只想在看到“NOT”之后才开始添加“NOT”,那么下面是一个可能有效的算法:

seen_not = False
output_list = []
for item in input_list:
    if seen_not:
        output_list.append("NOT_" + item)
    else:
        output_list.append(item)

    if item == "not":
        seen_not = True

我们构造一个新的列表,从旧列表中逐个添加项。如果我们已经在旧列表中看到“not”,我们只需将修改后的单词附加到新列表中。你知道吗

编辑:我将该代码转换为一个名为mod_list的函数,并在python解释器中进行了尝试:

>>> mod_list(['I', 'did', 'not', 'enjoy', 'the', 'movie'])
['I', 'did', 'not', 'NOT_enjoy', 'NOT_the', 'NOT_movie']

搜索not的索引,然后更改索引后面的列表部分怎么样?你知道吗

words = ['I', 'did', 'not', 'enjoy', 'the', 'movie']

try:
    idx = words.index('not') + 1
except ValueError:
    pass
else:
    words[idx:] = map(lambda s: 'NOT_' + s, words[idx:])

print words

结果:

['I', 'did', 'not', 'NOT_enjoy', 'NOT_the', 'NOT_movie']

相关问题 更多 >

    热门问题