Reputation: 1047
Is there a way to ask for user input and turn their input into a list, tuple, or string for that matter? I want a series of numbers to insert into a matrix. I could tell them to type all the numbers into the console with no spaces and iterate through them but are there any other ways to do this?
Upvotes: 5
Views: 7870
Reputation: 123
if you want to have a list that automatically places a comma whenever it finds a space between numbers use this:
query=input("enter a bunch of numbers: ")
a_list = list(map(int,query.split()))
print(a_list)
*split() will split them with commas, without input
*eg. 1 2 3 4 5 = [1, 2, 3, 4, 5]
Upvotes: 0
Reputation: 25478
NumPy supports MATLAB-style matrix definitions if you're using it:
import numpy as np
s = raw_input('Enter the matrix:')
matrix = np.matrix(s)
e.g.
Enter the matrix:1 2 3; 4 5 3
sets the matrix
to:
matrix([[1, 2, 3],
[4, 5, 3]])
Separate entries on each row by spaces and rows by semicolons.
Upvotes: 2
Reputation: 238111
You can simply do as follows:
user_input = input("Please provide list of numbers separated by comma, e.g. 1,2,3: ")
a_list = list(map(float,user_input.split(',')))
print(a_list)
# example result: [1, 2, 3]
Upvotes: 8