python - python嵌套反向循环
问题描述
我正在尝试创建一个与 for 循环嵌套的反向循环,一旦 for 循环满足某个标准,然后反向循环就会启动,以获取我正在搜索的所需信息,基于第二个一致的标准,我知道。通常会执行 for 循环来查找所需的信息;但是,我只知道标准,除了在标准之前列出的信息之外,我不知道所需的信息,并且可以采用三种不同格式之一。我正在使用 Python 3.6。
编辑:看起来让我失望的是“我正在寻找的东西”的不同格式。为简化起见,只需使用 1 种特定格式,我想要的信息可以与我不想要的信息分组。
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']
解决方案
我昨天回答了一个类似的问题,所以我会给你代码并解释你如何实现它。
首先你需要一个你已经拥有的列表,太棒了!让我们称之为
wordlist
。现在您需要一个代码来查找它
for numbers in range(len(wordlist)):
if wordlist[numbers][0] == 'the string im looking for':
print(wordlist[numbers])
推荐阅读
- php - 数组中的总计值并按新索引分组
- c# - HttpWebRequest - 请求被中止:无法创建 SSL/TLS 安全通道
- python - Django 覆盖 Django 针对 UniqueConstraint 错误显示的错误消息?
- c# - 调用 API 时使用 JWT 的困惑
- python - Pandas 使用 ExcelWriter 保存重复的 Excel 工作表
- elasticsearch - 在 ElasticSearchch 中按多个字段和前 10 个问题和答案进行汇总
- amazon-web-services - CloudFront:为什么管理员无权执行失效操作?
- javascript - 闪烁的通知栏
- kdb - kdb/q:生成所有可能的长度为 N 的“字符串”
- wso2 - 在 WSO2 IS 5.9.0 中,如何借助 API 配置密码策略和登录策略?