简体   繁体   中英

How to take input as an array from user in python using loops?

I want to get an input from the user to store data in array. Let's say size of array is stored in a variable "n" and it is assigned 5. Now I want to have a size of array which will store only 5 values based on n but in run time. Like using arr = input() which should accept input separated by spaces not commas and that too in one line which means it should accept in like 1 2 3 4 5 and if I print arr I should get the above arr separated with commas [1, 2, 3, 4, 5] input

5 ( Size of Array)
1 2 3 4 2 2 2 (Array exactly like spaces entered in the shell)
array_elem = list(map(int, input().split(' ')))

I tried this. I am not sure how to do it.

If I have to consider loops then, is this the correct way -

for i in range(5):
    arr = list(map(int, input().split(' ')))

I would use, you do not need the loop:

string = input()
arr = list(map(int, string.split(' ')))

You can input the numbers with commas and then do a split:

>>> arr = list(map(int, input().split(',')))
1,2,3,4,5
>>> arr
[1, 2, 3, 4, 5]

Or you can do with spaces:

>>> arr = list(map(int, input().split(' ')))
1 2 3 4 5
>>> arr
[1, 2, 3, 4, 5]

Edit: If you want to use loop, then here is the code:

>>> n = int(input('How many elements: '))
>>> arr = []
>>> for _ in range(n):
...     arr.append(int(input()))
2
3
4
5
6
>>> arr
[2, 3, 4, 5, 6]

if you are trying to add arrays to the arr

arr=[]
for i in range(2):
    arr.append(list(map(int, input().split(' '))))
print(arr)

and its output for 1 2 , 3 4 will be

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

if you are trying to add elements to the same arr

arr=[]
for i in range(2):
    arr+=(list(map(int, input().split(' '))))
print(arr)

and its output for 1 2 , 3 4 will be

[1, 2, 3, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM