【问题标题】:The reason that python runs out of memory when loops are used to search through lists使用循环搜索列表时python内存不足的原因
【发布时间】:2019-06-26 14:33:08
【问题描述】:

这是我编写程序所需的问题:

编写一个程序来打开文件 romeo.txt 并逐行读取。对于每一行,使用 split 函数将该行拆分为单词列表。 对于每个单词,检查该单词是否已经在列表中。如果单词不在列表中,请将其添加到列表中。程序完成后,按字母顺序排序并打印结果单词 顺序。

文本文件包括以下几行:

但是柔和的光线从那边的窗户打破 它是东方,朱丽叶是太阳 升起美丽的太阳,杀死嫉妒的月亮 谁已经病入膏肓,悲痛欲绝

我试图理解为什么当我使用此代码时 Python 返回“MemoryError”:

fhand=open("romeo.txt")
binlist=["a"]
for myline in fhand:
    myline=myline.rstrip()
    mylist=myline.split()
    for word in mylist:
        for binword in binlist:
            if word==binword:
                continue
            else:
                binlist.append(word)
binlist.sort()
print(binlist)

但是,这段代码运行良好:

fhand=open("romeo.txt")
binlist=[]
for myline in fhand:
    myline=myline.rstrip()
    mylist=myline.split()
    for word in mylist:
        if word in binlist:
            continue
        else:
            binlist.append(word)
binlist.sort()
print(binlist)

【问题讨论】:

    标签: python list loops search memory


    【解决方案1】:

    检查您的内部 for 循环的逻辑。你是说:

    For each word in binlist:
        If word is EQUAL to binword, then proceed to the next word
        If word is NOT equal to binword, then add it to the end of binlist
    

    这意味着您的代码可以将单词添加到 binlist 的末尾,然后继续遍历列表。这可能会导致无限循环,因为您将继续迭代不断扩大的列表。

    【讨论】:

      【解决方案2】:

      使用第一个代码,您可以多次将单词添加到列表中,即使该单词已经在 binlist 中。你还在修改(附加)列表,同时循环遍历同一个列表,这会导致列表不断扩展和永远不会终止的循环。

      你可能想用一组来代替

      fhand=open("romeo.txt")
      binlist={}
      for myline in fhand:
          set.update(myline.split())
      binlist = sorted(binlist)
      print(binlist)
      

      【讨论】:

        猜你喜欢
        • 2020-12-09
        • 2011-08-03
        • 1970-01-01
        • 2014-05-12
        • 2012-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多