我正在尝试创建一个嵌套了for循环的反向循环,一旦for循环满足某个条件,那么反向循环就会启动,以获取我所搜索的所需信息,基于我所知道的第二个、一致的条件。通常会执行for循环来查找所需的信息;但是,我只知道准则,不知道所需的信息,只知道准则之前列出的信息,可以是三种不同格式中的一种。我使用的是python3.6。你知道吗
编辑:看起来让我讨厌的是“我在找什么”的不同格式。为了简化它,我们只需使用一种特定的格式,我想要的信息可以与我不想要的信息分组。你知道吗
searchList = [['apple'], ['a criterion for'],
['what Im looking for'], ['a criterion for what Im looking for not what Im looking for'],
['fish'], ['coffee'], ['oil']]
saveInformation = []
for n in range(len(searchList)):
if 'coffee' in searchList[n]:
for x in range(n, 0, -1):
if 'a criterion for' in searchList[x]:
#this part just takes out the stuff I don't want
saveInformation.append(searchList[x])
break
else:
# the reason for x+1 here is that if the above if statement is not met,
#then the information I am looking for is in the next row.
#For example indices 1 and 2 would cause this statement to execute if index
#3 was not there
saveInformation.append(searchList[x+1])
break
预期产量
saveInforation = ['what Im looking for']
相反,我得到的结果是
saveInforation = ['oil']
我认为最好不要嵌套for循环,而是将问题分成不同的步骤。甚至最好为每个步骤创建一个单独的函数。你知道吗
我并不完全清楚您的要求,但我认为这正是您所需要的:
我昨天回答了一个类似的问题,所以我将给您代码并解释如何实现它。你知道吗
您可以使用一个小列表来获得类似的效果:
这将执行您需要的检查,仅将您想要的项添加到新列表中,即使如此,也仅当您的条件项存在时。你知道吗
你甚至可以添加更多的项目来搜索,比如:'
然后在列表中用
if item in itemsWanted
替换if item == 'im looking for'
作为补充说明,您可以通过在开始时执行if语句来减少执行的检查数:
相关问题 更多 >
编程相关推荐