处理 python(10 万行)中大量输入的最佳方法是什么?

What is the best way to handle large inputs in python (100 k lines)?

我需要处理 100k 行的输入(每行包含一个字符串)并在每行上执行一个函数。该函数将为每个字符串 return 一个结果,并将其打印到控制台。 这样做的最佳方法是什么?

我目前的尝试是:

strings = []
for i in xrange(int(input())):
    strings.append(raw_input())

更多背景:我想在 Hackerrank 上解决一个问题。输入可以如下所示(由 Hackerrank 提供支持): https://hr-testcases.s3.amazonaws.com/4187/input02.txt?AWSAccessKeyId=AKIAINGOTNJCTGAUP7NA&Expires=1420719780&Signature=iSzA93z7GKVIcn4NvdqAbbCOfMs%3D&response-content-type=text%2Fplain

您不需要将整个文件存储在内存中,因为您在读取文件时正在计算和打印结果。

因此,只需逐行读取文件,进行计算并打印结果:

with open('large-file.txt') as the_file:
    for line in the_file:
       result = do_something_with(line)
       print(result)

使用stdin流,stdin就像一个文件流

import sys
for line in sys.stdin
  do_work(line)