【问题标题】:Performing actions while iterating over a list在迭代列表时执行操作
【发布时间】:2023-03-17 14:28:01
【问题描述】:

我正在遍历一个列表

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

我需要将起始词和停止词之间的所有数据附加到另一个列表中,我该怎么做?

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

例如:

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.

【问题讨论】:

  • 您能向我们展示您的代码吗?目前尚不清楚您要做什么。

标签: python list iteration


【解决方案1】:

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

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']

希望这会有所帮助!

【讨论】:

  • 第二种方案基本上是Nathan方案的固定版本。
  • @JanChristophTerasa 没错!他的版本是在列表中添加一个列表以及使用起始元素,这不是 OP 的意图。所以我在答案中添加了正确的版本
  • 第一个版本正是我需要的,谢谢!
【解决方案2】:

很高兴获得更多信息,但根据您提供的信息,您可以使用“开始”和“停止”词的索引来附加到新列表:

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']]

【讨论】:

  • 您应该使用list.extend 删除不必要的额外列表。如果您附加一个列表切片,它将附加一个列表,而不是列表的各个元素。另一方面,您可以直接使用切片列表,如果您将+1 添加到起始索引,它已经是所需元素的列表。
  • @NathanThomas 谢谢,很好的解决方案,它几乎解决了我的问题,但是这个停用词可能出现在列表的前面,所以我需要程序在开始词之后开始记录它并在第一个停用词之后停止名单。我很遗憾没有向您提供那条信息,谢谢,好点!
猜你喜欢
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 2014-12-29
  • 1970-01-01
相关资源
最近更新 更多