遍历列表时执行操作

时间:2020-06-20 19:01:25

标签: python list iteration

我正在遍历列表

action

我需要在开始和结束词之间附加所有数据,该怎么办?

停用词在列表中出现几次。因此,当循环在途中找到第一个停用词时,应停止添加。

例如:

xxx
yyy
**start word**
xxx
yyy
zzz
**stop word** 
break

2 个答案:

答案 0 :(得分:2)

您可以维护一个布尔值,以指示何时开始追加和何时停止追加。为此,您可以编写类似-

的代码
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']

在这里,startend是开始和结束词,您可以根据程序的开始和结束词对其进行修改。


另一种可能的解决方案是获取您的起始词和终止词的索引,然后仅将这些索引之间的元素存储到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']

希望这会有所帮助!

答案 1 :(得分:1)

很高兴获得更多信息,但是从提供的内容来看,您可以使用“开始”和“停止”两个词的索引附加到新列表中:

list1 = ["xxx", "yyy", "start_word", "xxx", "yyy", "zzz", "end_word"]

a = list1.index("start_word")
b = list1.index("end_word")

list2 = []
list2.append(list1[a:b])

print(list2)

输出:

[['start_word', 'xxx', 'yyy', 'zzz']]
相关问题