5

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 3

8

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]
Sign up to request clarification or add additional context in comments.

4 Comments

nice thanks. Literally just learned about maps today so I didn't think to use it
should really use a try/except when casting, there are many ways this will raise an error
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']
You both right. My answer is one of many possibilities. Please feel free to make alternative answers.
2

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

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.