0

I am using input().split() method to input elements in a list from a space separated single line input in python. However, I am unable to find a way to limit the inputs. As in if user is giving more than desired inputs in single line, is there any method to check that?

I read about assert method, but couldn't implement it correctly.

import numpy
m,n = map(int,input().split())
a = numpy.array([input().split() for i in range(n)], int)
print(a)

Input:

3 2

1 2 3 4 5

3 4 5 6 7

output:

[[1 2 3 4 5]
 [3 4 5 6 7]]

I want the row should contain 3 elements per row and rest of the entries should be avoided/discarded without any errors. Please help. Expected Output:

[[1 2 3]
 [3 4 5]]
Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
pallavi
  • 3
  • 2

2 Answers2

0
def get_input():
        user_input = input("Input: ")

        split_input = user_input.split()

        if len(split_input) > 3:
                raise Exception("Too much input")

        return split_input

Instead of rasing an exception, you can have some output or another input attemp etc.

Joshua Nixon
  • 1,379
  • 2
  • 12
  • 25
0

your code is basically there, I'd just use list slicing to limit the maximum number of elements, e.g. lst[:3] evaluates to a list of at most 3 elements.

in your example, this would be:

import numpy
m,n = map(int,input().split())
a = numpy.array([input().split()[:m] for i in range(n)], int)
print(a)
Sam Mason
  • 15,216
  • 1
  • 41
  • 60