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?
3 Answers
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]
4 Comments
Joseph hooper
nice thanks. Literally just learned about maps today so I didn't think to use it
Padraic Cunningham
should really use a try/except when casting, there are many ways this will raise an error
martineau
I would also recommend separating elements by spaces and using plain
.split() because it handles multiple spaces between items automatically. i.e. '1 2 3 4 5'.split() --> ['1', '2', '3', '4', '5']Marcin
You both right. My answer is one of many possibilities. Please feel free to make alternative answers.
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.
Comments
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]