Python- Turning user input into a list

2020-04-06 15:37发布

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?

标签: python input
3条回答
Deceive 欺骗
2楼-- · 2020-04-06 16:30

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楼-- · 2020-04-06 16:34

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]

查看更多
趁早两清
4楼-- · 2020-04-06 16:36

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]
查看更多
登录 后发表回答