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
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)
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With