代码之家  ›  专栏  ›  技术社区  ›  joseph

在python中,什么是逐行读取标准In的功能性、内存效率高的方法?

  •  0
  • joseph  · 技术社区  · 6 年前

    https://stackoverflow.com/a/1450396/1810962 另一篇文章的答案几乎达到了:

    import sys
    data = sys.stdin.readlines()
    preProcessed = map(lambda line: line.rstrip(), data)
    

    我现在可以在中的线路上操作了 data

    1 回复  |  直到 6 年前
        1
  •  4
  •   Thierry Lathuille    6 年前

    只是重复一下 sys.stdin ,它将在行上迭代。

    map filter 如果你愿意的话。进入的每一行都将通过管道,在此过程中不会生成任何列表。

    以下是每种方法的示例:

    import sys
    
    stripped_lines = (line.strip() for line in sys.stdin)
    lines_with_prompt = ('--> ' + line for line in stripped_lines)
    uppercase_lines = map(lambda line: line.upper(), lines_with_prompt)
    lines_without_dots = filter(lambda line: '.' not in line, uppercase_lines)
    
    for line in lines_without_dots:
        print(line)
    

    在行动中,在终端中:

    thierry@amd:~$ ./test.py 
    My first line
    --> MY FIRST LINE 
    goes through the pipeline
    --> GOES THROUGH THE PIPELINE
    but not this one, filtered because of the dot. 
    This last one will go through
    --> THIS LAST ONE WILL GO THROUGH
    

    只是,在哪里 地图 stdin :

    import sys
    
    uppercase_lines = map(lambda line: line.upper(), sys.stdin)
    
    for line in uppercase_lines:
        print(line)
    

    在行动中:

    thierry@amd:~$ ./test2.py 
    this line will turn
    THIS LINE WILL TURN
    
    to uppercase
    TO UPPERCASE