Home > Back-end >  How to make an input of unorganized numbers into an array/matrix and sum specific numbers
How to make an input of unorganized numbers into an array/matrix and sum specific numbers

Time:08-08

I have this problem where i get an console input that is not an array/matrix, it's just a bunch of numbers per line separated by a space. How do i turn them in a actual array?

OBS about the input (the input it's not an txt or csv, it's directly the terminal inputing me numbers separated by space)

My given input is like this:

4 3 2 1 3 4 2 2 3 3 2 1 2 3
4 4 1 3 2 1 4 2 4 1 1 1 4 3
4 4 4 1 2 2 3 4 2 1 1 2 1 1
1 3 2 2 2 3 2 3 3 4 3 2 4 1
1 3 3 2 2 2 4 4 3 2 1 4 4 3
2 1 4 3 2 2 2 4 3 1 2 3 1 1
4 1 3 4 2 4 3 3 2 4 2 2 1 1
1 1 4 3 4 1 3 3 2 2 1 1 3 1
4 2 1 1 3 3 1 2 3 2 2 1 2 3

And for now i'm doing this:

string_data = input()
arr = [[int(num) for num in sublist.split()] for sublist in string_data.split('\n') if len(sublist)>0]
print(arr)

This solution kinda works.. but only for the first line, so the input from the code above will be:

[4, 3, 2, 1, 3, 4, 2, 2, 3, 3, 2, 1, 2, 3]

I need to find a way to merge this into an full array without creating the code that i wrote for each line. My main problem is to turn my input into an array so that I can add every time the number 2 appears.... so if it appears 5 times, the program needs to read it and return me the number 10

CodePudding user response:

Use np.fromstring

import numpy as np

string_data = str(input())

np.fromstring(string_data, dtype=int, sep="\n")
  • Related