Home > database >  How to split data from standard input?
How to split data from standard input?

Time:11-13

I have some number of lines in data for input:

data = sys.stdin.readlines()

Find out the number of lines:

l = len(data)

How can I split this data into variables? For example I have the following input:

1 0
2 2
0 0 1 1
0 1 1 0

First come 2 numbers - n, m

Then m lines with 4 values - x1, y1, x2, y2

I tried to do this:

for _ in range(l):
    n, m = map(int, data.readline().split())

    some_list = []
    for _ in range(m):
        x1, y1, x2, y2 = map(int, data.readline().split())
        some_list.append([x1, y1, x2, y2])
    some_function_with_given_part_of_data()

But it doesn't work correctly.

CodePudding user response:

just handle it section by section

data = sys.stdin.readlines()
indexer = 0
while indexer < len(data) - 1:
    n, m = map(int, data[indexer].split(" "))
    indexer = indexer   1
    some_list = []
    for _ in range(m):
        x1, y1, x2, y2 = map(int, data[indexer].split(" "))
        some_list.append([x1, y1, x2, y2])
        indexer = indexer   1
    print(some_list)

input

1 0
2 2
0 0 1 1
0 1 1 0

output

[]
[[0, 0, 1, 1], [0, 1, 1, 0]]

note

you might want to remove empty arrays from the some_list array

CodePudding user response:

Simply use input() instead of sys.stdin.

The value of m determines how many lines you need to read. Then all you have to do is read the rest in a for loop:

n, m = map(int, input().split())
lines = [[int(value) for value in input().split()] for _ in range(m)]

You can access the values by index instead of names. lines is a list of lists.

First value of the first line(your x1) would be lines[0][0] for example.

  • Related