简体   繁体   English

在迭代列表时执行操作

[英]Performing actions while iterating over a list

I am iterating over a list我正在遍历一个列表

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

I need to append to another list all the data between start and stop words, how do I do that?我需要 append 到另一个列表开始和停止词之间的所有数据,我该怎么做?

The stop word appears couple times in the list.停用词在列表中出现了几次。 So the appending should be stopped when loop finds first stop word on it's way.因此,当循环在其途中找到第一个停止词时,应停止附加。

For example:例如:

list = [1,2,3 ... 1000]
new_list = []
for i in list:
    # Once i = 5 I need to start appending i values to new_list until i = 25.

You can maintain a boolean to indicate when to start appending and when to stop appending.您可以维护一个 boolean 来指示何时开始追加以及何时停止追加。 For this, you could write your code something like -为此,您可以编写类似的代码 -

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)
    

Output: Output:

['Hello World', 'Bye']

Here, start and end are the start and stop words, you could modify them as per your start and stop words of the program.这里, startend是开始词和停止词,您可以根据程序的开始词和停止词对其进行修改。


Another possible solution would be to fetch the index of your start and stop words and just store the elements between those indexes into your another_list as follows -另一种可能的解决方案是获取开始词和停止词的索引,并将这些索引之间的元素存储到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)
    

Output: Output:

['Hello World', 'Bye']

Hope this helps !希望这可以帮助 !

Would be great to get more information, but from what you've provided, you could use the index of your "start" and "stop" words to append to a new list:获得更多信息会很棒,但是根据您提供的信息,您可以使用 append 的“开始”和“停止”词的索引到一个新列表:

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)

Output: Output:

[['start_word', 'xxx', 'yyy', 'zzz']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM