Python- Turning user input into a list

2020-04-06 16:26发布

问题:

Hey guys is there anyway 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?

回答1:

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]


回答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.



回答3:

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]



标签: python input