How to read inputs from the user for array in python?
Array is a collection of similar data elements. It may be a single dimensional, two dimensional or more..
Let us create an array of elements and read inputs from the
user. For this purpose, let us use the built-in functions like input(), split()
and map(). Based on the data type, you can use these functions.
Numpy directly converts the list into array.
Python Program to read inputs from the user for 1D array:
1D array
has a set of elements arranged in sequential manner. Let us create and read the
input.
Code:
import numpy as np1
# Read the number of elements
no = int(input("Enter the number of elements: "))
# Read the array of elements
s_arr = list(map(int, input(f"Enter {no} numbers
separated by space: ").split()))
# Let us Convert to NumPy array
s_arr = np1.array(s_arr)
print("Array:", s_arr)
Output:
Enter the number of elements: 5
Enter 5 numbers separated by space: 34 45 56 67 78
Array: [34 45 56 67 78]
Next one is 2D array.
Python Program to read inputs from the user for 2D array:
This
program reads the number of rows and columns. It reads the elements one by one.
- · First, read the input as list. Next, split the numbers separated by space.
- · Reshape the data into array.
- · Finally, print the data.
Code:
import numpy as np1
a_rows = int(input("Enter the number of rows: "))
a_cols = int(input("Enter the number of columns:
"))
print(f"Enter {a_rows*a_cols} numbers separated by
space:")
data = list(map(int, input().split()))
s_arr = np1.array(data).reshape(a_rows, a_cols)
print("The 2D Array is:\n", s_arr)
Output:
Enter the number of rows: 3
Enter the number of columns: 3
Enter 9 numbers separated by space:
2 3 4 5 6 7 8 9 1
The 2D Array is:
[[2 3 4]
[5 6 7]
[8 9 1]]
These are the methods to read data elements from the user
for the array. Hope, this code is useful to you. Keep Coding!!!!
Comments
Post a Comment