【问题标题】:Python nested for loop to match strings in array elements to a filePython嵌套for循环以将数组元素中的字符串匹配到文件
【发布时间】:2012-10-09 21:40:08
【问题描述】:

我的代码的目的是遍历数组中的每个元素,将元素转换为字符串,然后从包含该字符串的另一个文件返回行。我的代码是:

    for element in myarray:
         elementstring=''.join(element)
         for line in myfile:
              if elementstring in line:
                  print line

如果代码运行,它只会对第一个元素起作用。谁能解释这是为什么?

【问题讨论】:

  • 什么是myfile?是文件对象还是字符串数组?
  • myfile 是一个文件对象,用 myfile=open('location','r') 打开

标签: python file for-loop python-2.7 nested-loops


【解决方案1】:

发生这种情况是因为当您通读一次文件的行时,您会到达文件的末尾并且没有剩余的行可以读取。您需要关闭文件并重新打开它以读取每个element

这是一种方法:

for element in myarray:
    elementstring=''.join(element)
    with open('path/to/myfile') as myfile:
        for line in myfile:
            if elementstring in line:
                print line

或者,如果这是一个足够小的文件,您可以通过预先缓存文件中的行来避免磁盘中的多个reads 来减少运行时间,如下所示:

myfile = [line.rstrip('\n') for line in open('path/to/myfile')]
for element in myarray:
    elementstring=''.join(element)
    for line in myfile:
        if elementstring in line:
            print line

【讨论】:

  • 第一个例子是有问题的,因为它没有关闭文件,所以没有释放操作系统相关的资源。考虑使用 with 语句或在 for 循环后手动关闭文件。
  • 啊,是的,第一个示例完美运行!非常感谢检查员小工具。还有沙丘,谢谢你的建议!
  • @Dunes:已编辑以使用 with 修复。那应该在循环结束时杀死文件指针
【解决方案2】:

您浏览了一个文件...将指针移到末尾...您需要重新打开文件或myfile.seek(0) ...但是您的代码还有其他一些问题。没有看到myarray就很难回答

【讨论】:

  • 感谢您的帮助。我的数组是:[['IGHV1-18*01'],['IGHV1-18*02'],['IGHV1-18*03']]
【解决方案3】:
with open(myfile) as f:
    lines=[x for x in f] #store all lines in a list first
    for element in myarray:    #now iterate over myarray
         elementstring=''.join(element)
         for line in lines:            #now iterate over individual line from lines
              if elementstring in line:
                  print line

【讨论】:

    【解决方案4】:

    正如其他人所说,文件不是集合。文件是按顺序读取的,每次迭代都需要使用 seek 函数返回到第一行。

    无论如何,这并不是做你想做的最好的方式。

    从文件读取通常比从 RAM 读取慢(即使有缓存),所以最好让主循环遍历文件。

    最好事先计算外部数组上的所有字符串值。

    最后,有很多算法可以在文件(或更大的字符串)中搜索一组字符串,您可能会考虑使用这些算法。

    这是您的代码的优化版本:

    strs = [' '.join(element) for element in myarray]
    for line in open(''path/to/myfile'):
        for elementstring in strs:
             if elementstring in line:
                  print line
    

    【讨论】:

    • 我明白了,谢谢lcfseth的解释!我是 python 新手,不知道。
    猜你喜欢
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多