【问题标题】:python loop with boolean statement only runs once带有布尔语句的python循环只运行一次
【发布时间】:2021-11-24 11:13:20
【问题描述】:
def test(wList,fList):
    outfile = open("ignore.txt","w")
    stopWords = ['in','it','a','an','and','to','of','the','for',]

    for i in range(len(wList)):
        x=0
        if wList[i]==stopWords[x]:
            print(stopWords[x],fList[i], file=outfile)
            x=x+1

我正在尝试比较两个不同大小的列表(wList 和 stopWords)。当它们在 wList[i] 和 stopWords[x] 处匹配时,我想转到 stopWords 中的下一个单词。

【问题讨论】:

  • 每次迭代都将x 重置为零。也许您想在循环之前移动分配?
  • @StevenRumbalski 成功了。但是我仍然有一个小问题,stopWords 中的单词“an”在 wList 中根本不存在,并且它阻止了其余单词的比较。如果 wList 中不存在,有没有办法转到 stopWords 中的下一个单词?
  • @Jack 您的比较标准含糊不清。您能否提供输入和预期输出样本,以便我们更好地理解它?
  • @kiruwka 我做了一些研究,发现了真正的问题。在搜索 wList 时,我一次只查找一个单词。因此,我可以传递列表中的其他单词,它不会注册为匹配项。有没有办法可以在每次成功后将 i 重置为零?
  • 如果你给出一个示例输入以及程序应该输出什么,就会更容易理解。

标签: python list loops boolean


【解决方案1】:

类似的东西?

def test(wList,fList):
    with open("ignore.txt","w") as outfile:
        stopWords = ['in','it','a','an','and','to','of','the','for',]

        for i in range(len(wList)):
            for word in stopWords:
                if wList[i]==word:
                    print(word, fList[i], file=outfile)
                    break

【讨论】:

  • 是的。你是神。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 2013-10-09
相关资源
最近更新 更多