Python 如何修改术语列表中特定术语之后的所有术语?

Python 如何修改术语列表中特定术语之后的所有术语?,python,list,Python,List,我有一个这样的单词列表: list = ['I', 'did', 'not', 'enjoy', 'the', 'movie'] 因此,目的是,如果单词列表中出现“not”,那么下面的所有单词都应该在其左侧连接一个“not”。例如,上面列表的输出应为: output_list = ['I', 'did', 'not', 'NOT_enjoy', 'NOT_the', 'NOT_movie'] 如果您只想在看到“NOT”之后才开始添加“NOT”,那么以下是一个可能有效的算法: seen_no

我有一个这样的单词列表:

 list = ['I', 'did', 'not', 'enjoy', 'the', 'movie']
因此,目的是,如果单词列表中出现“not”,那么下面的所有单词都应该在其左侧连接一个“not”。例如,上面列表的输出应为:

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

如果您只想在看到“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']

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

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()
您可以查看一下Ideone.com上的输出。

一个标志,两个(错误)->一个循环可以找到它

  • 如果没有找到“not”的位置,则标志为false

  • 如果标志为false,则输出不带“NOT_uu”的单词,否则输出前缀为“NOT_uu”


以下是参考代码(不够好,但请保留以供提醒):


另外,
list
对于python中的列表来说可能不是一个好的变量名。

对于列表理解来说是一个完美的例子。@mic4ael可能不是,就像“not”后面的这个词一样?用这种方式表达会很尴尬。@mic4ael:我不太确定列表理解是最好的方法。是的,我觉得这是一种足够简单、足够普遍的模式,给出完整的答案在道德上没有错,但我明白你的意思。
# -*- coding: utf-8 -*
# Filename: test.py

__author__ = 'piratf'

flagWord = 'not'
prefixWord = 'NOT_'

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

flag = -1;
for x in range(0, len(srcList)):
    if srcList[x] == flagWord:
        flag = x;
        break;
if (flag != -1):    
    for x in range(flag + 1, len(srcList)):
        srcList[x] = prefixWord + srcList[x];

print (srcList)