Reputation: 1972
I am trying to get multiple inputs in a single line in python. This are the kind of inputs I am trying to take, the first line consists of the number of lines of input I will take:
3
1 2 3
4 3
8 9 6 3
Is there any way to take that kind of input, without knowing how many inputs are going to be given per line?
Upvotes: 3
Views: 307
Reputation: 11
When you want to get two or more integer values from the user :
Method 1 : Using map() and split() function
// Taking Common Variable v to get multiple user input
v = input("Enter the three numbers separated by a whitespace : ")
// Using map() and split() function to assign values to three variables a,b and c
a,b,c = map(int(),v.split())
Explanation :
In this way we can provide three integer user input values to three different variables. For Floating values, just replace int() function with float()
Method 2 : Using list() , map() and split() methods:
// Taking a variable to store the list of values
L = list(map(int(),input("Enter three values separated by space).split()))
Explanation :
In this way we can provide List of integers user input values to a list variable. For Floating values, just replace int() function with float()
Method 3 : Using List Comprehension Method() :
// Unpacking the variables using list comprehension
x,y,z = [int(x) for x in input("Enter two values : ").split()]
In this way we can provide three integer user input values to three different variables. For Floating values, just replace int() function with float()
Upvotes: 0
Reputation: 11
you can use the map function that will append the inputs to a list if , suppose you have to take any n no of inputs
arr = list(map(int,input().split()))
all the elements entered will be stored as integer in arr list.
Upvotes: 0
Reputation: 111
You could use.
separator = ' '
parameters = input("parameters:").split(separator)
e.g.
Python 3.6.5 (default, Mar 30 2018, 06:42:10)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> separator = '-'
>>> parameters = input("parameters:").split(separator)
parameters:5-6
>>> parameters
['5', '6']
>>>
Upvotes: 4