简体   繁体   中英

How to read “n” lines at a time from stdin?

Consider the stdin has the following entries:

2  
a     
b     
3
d   
e   
f   

Now I would like to first read the number using n= sys.stdin.readline() and then read the next n lines using a function ReadNLines(n) into a list.

So the expected output is:

List1 = ['a','b']  
List2 = ['d','e','f']

Here is what I have tried. And I am looking for better timing performance.

import sys
def ReadNLines(n):
    List =[]
    for line in range(n):
        List.append(sys.stdin.readline())
    return List

if __name__ == "__main__":
    n = sys.stdin.readline()
    List1 = ReadNLines(n)
    n = sys.stdin.readline()
    List2 = ReadNLines(n)

You need to remove the newline that sys.stdin.readline() includes in the result. And you need to convert n to an integer.

import sys
def ReadNLines(n):
    List =[]
    for _ in range(n):
        List.append(sys.stdin.readline().strip())

if __name__ == "__main__":
    n = int(sys.stdin.readline().strip())
    ReadNLines(n)
    n = int(sys.stdin.readline().strip())
    ReadNLines(n)

Since you never use the line variable, the convention is to use _ as a dummy variable. You can also convert the function into a list comprehension:

def readNLines(n):
    return [sys.stdin.readline().strip() for _ in range(n)]

I think this does what you want:

import sys

def read_n_lines(n):
    return [sys.stdin.readline().rstrip() for _ in range(n)]

if __name__ == "__main__":
    count = 0
    while True:
        n = sys.stdin.readline().rstrip()
        if not n:  # Blank line entered?
            break  # Quit.
        n = int(n)
        result = read_n_lines(n)
        count += 1
        print(f'List{count} = {result}')
    print('done')

Sample run — Enter key was pressed to end each line of input:

2
a
b
List1 = ['a', 'b']
3
d
e
f
List2 = ['d', 'e', 'f']

done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM