您可以维护一个布尔值来指示何时开始追加以及何时停止追加。为此,您可以编写类似的代码 -
old_list = ['axz','bbbdd','ccc','start','Hello World','Bye','end','ezy','foo']
another_list=[]
append_to_list = False # Boolean to indicate if we should append current element
start_word = 'start'
end_word = 'end'
for element in old_list:
if element == end_word :
append_to_list = False
if append_to_list : # Appending to list if the Boolean is set
another_list.append(element)
if element == start_word :
append_to_list = True
print(another_list)
输出:
['Hello World', 'Bye']
这里,start 和 end 是起始词和终止词,您可以根据程序的起始词和终止词修改它们。
另一种可能的解决方案是获取起始词和停止词的索引,并将这些索引之间的元素存储到您的 another_list 中,如下所示 -
old_list = ['axz','bbbdd','ccc','start','Hello World','Bye','end','ezy','foo']
start_idx = old_list .index("start")
stop_idx = old_list .index("end")
another_list = old_list[start_idx+1:stop_idx]
print(another_list)
输出:
['Hello World', 'Bye']
希望这会有所帮助!