【问题标题】:Improving the speed of a python script提高python脚本的速度
【发布时间】:2015-09-27 04:57:48
【问题描述】:

我有一个包含字符串列表的输入文件。

我从第二行开始每隔四行迭代一次。

从每一行中,我从第一个和最后 6 个字符创建一个新字符串,并且仅当该新字符串是唯一的时才将其放入输出文件中。

我为此编写的代码有效,但我正在处理非常大的深度测序文件,并且已经运行了一天并且没有取得太大进展。因此,我正在寻找任何建议,以尽可能加快速度。谢谢。

def method():
    target = open(output_file, 'w')

    with open(input_file, 'r') as f:
        lineCharsList = []

        for line in f:
            #Make string from first and last 6 characters of a line
            lineChars = line[0:6]+line[145:151] 

            if not (lineChars in lineCharsList):
                lineCharsList.append(lineChars)

                target.write(lineChars + '\n') #If string is unique, write to output file

            for skip in range(3): #Used to step through four lines at a time
                try:
                    check = line    #Check for additional lines in file
                    next(f)
                except StopIteration:
                    break
    target.close()

【问题讨论】:

  • 我假设问题是一旦 lineCharsList 变大,脚本会变得很慢。我没有任何建议,但这很可能是问题所在。
  • 我也是这么想的。 RAM 应该不是问题,因为我正在开发一个有足够余量的计算集群。但我不确定是否有比将所有内容存储在这样的列表中更好的方法。
  • 顺便说一句,您可以在with 语句中包含输出文件 - with open(input_file, 'r') as f, open(output_file, 'w') as target:
  • 你用的是什么 Python 版本?

标签: python


【解决方案1】:

尝试将lineCharsList 定义为set 而不是列表:

lineCharsList = set()
...
lineCharsList.add(lineChars)

这将提高in 运算符的性能。此外,如果内存根本不是问题,您可能希望将所有输​​出累积到一个列表中并在最后全部写入,而不是执行多个 write() 操作。

【讨论】:

    【解决方案2】:

    你可以使用https://docs.python.org/2/library/itertools.html#itertools.islice:

    import itertools
    
    def method():
        with open(input_file, 'r') as inf, open(output_file, 'w') as ouf:
            seen = set()
            for line in itertools.islice(inf, None, None, 4):
                s = line[:6]+line[-6:]
                if s not in seen:
                    seen.add(s)
                    ouf.write("{}\n".format(s))
    

    【讨论】:

      【解决方案3】:

      除了按照 Oscar 的建议使用 set 之外,您还可以使用 islice 来跳过行,而不是使用 for 循环。

      this post 中所述,islice 在 C 中预处理迭代器,因此它应该比使用普通的普通 python for 循环快得多。

      【讨论】:

        【解决方案4】:

        尝试替换

        lineChars = line[0:6]+line[145:151]

        lineChars = ''.join([line[0:6], line[145:151]])

        因为它可以更有效,具体取决于具体情况。

        【讨论】:

          猜你喜欢
          • 2021-12-25
          • 1970-01-01
          • 2021-09-18
          • 1970-01-01
          • 2021-12-14
          • 1970-01-01
          • 1970-01-01
          • 2019-08-01
          • 1970-01-01
          相关资源
          最近更新 更多