How to take n numbers as input in single line in Python?

老子叫甜甜 提交于 2020-01-11 10:08:21

问题


like in c++ how can I ask user input upto a range

Below is the code to take user input in c++

#include<iostream>
using namespace std;
int main() {
    int array[50];
    cin>>n;
    //ask a list
    for(i = 0; i<n; i++){
        cin>>array[i];
    }
}

how can I ask user input like above in python3? (I dont want to take the inputs in different lines)


回答1:


There are various methods to do this. User can enter multiple inputs in single line separated by a white space. Let's say I want user to enter 5 numbers as

1 2 3 4 5

This will be entered in a single line. But keep in mind that any input is considered a string in python. So you'll have to convert these values into integer values. Also, you would need to access these entered values separately. For that, you can convert the values to integer and add them into list. In python, strangely enough, there are no arrays, but lists. So your code should look something like this:

mylist=list(map(int,input("Enter 5 numbers: ").split())

You might want to look at implementation of split() and map() functions. You can find them in the official documentation. But here is a little explanation: The map(func,seq) function will convert the input one by one to the function supplied, int in this case. This function is equivalent to a for loop which iterates over the elements one by one and applies some transformation function. The split() function will split the input by white spaces if no separator is supplied in the brackets. By default, map() function returns a map object. So to convert it into a list, we use list().

Hope this clarifies your doubt.




回答2:


This will convert numbers separated by spaces to be stored in ar:

ar = list(map(int, input().strip().split(' ')))


来源:https://stackoverflow.com/questions/48841186/how-to-take-n-numbers-as-input-in-single-line-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!