Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

easier way to get stdin-lines converted to "float/int" arrays in python

Tags:

I always want to learn better and shorter ways to code, so I have a pretty complicated input which I guess could be written way simpler:

I have an unknown size of float inputs and I want to turn every line into an array when the last input is a new line.

import sys
input_matrix = []
for line in sys.stdin:
    if line != '\n':
        str_input = line.split(" ")
        float_input = []
        for i in range(len(str_input)):
            float_input.append(float(str_input[i]))
        input_matrix.append(float_input)
    else:
        break

And the input is something like this:

2.0 9.0 3.2 0.1 2.0
10 19 2.0
18 20 1.0 1.5
like image 770
Tim4497 Avatar asked Jun 23 '18 00:06

Tim4497


1 Answers

The builtin iter has a second form specifically for this usecase.

One useful application of the second form of iter() is to read lines of a file [or stdin] until a certain line is reached.

Using this you can achieve the same result with a single list-comprehension.

input_matrix = [[float(x) for x in line.split()] for line in iter(input, '')]

print(input_matrix)

Output

2.0 9.0 3.2 0.1 2.0
10 19 2.0
18 20 1.0 1.5

[[2.0, 9.0, 3.2, 0.1, 2.0], [10.0, 19.0, 2.0], [18.0, 20.0, 1.0, 1.5]]
like image 121
Olivier Melançon Avatar answered Sep 16 '22 11:09

Olivier Melançon