Python- 将用户输入转换为列表
Python- Turning user input into a list
有没有办法请求用户输入并将他们的输入转换为列表、元组或字符串?我想要将一系列数字插入到矩阵中。我可以告诉他们在控制台中输入所有数字,不要有空格,然后遍历它们,但是还有其他方法可以做到这一点吗?
您可以简单地进行如下操作:
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]
NumPy 支持 MATLAB 风格的矩阵定义,如果您正在使用的话:
import numpy as np
s = raw_input('Enter the matrix:')
matrix = np.matrix(s)
例如
Enter the matrix:1 2 3; 4 5 3
将 matrix
设置为:
matrix([[1, 2, 3],
[4, 5, 3]])
每行的条目用空格分隔,行的条目用分号分隔。
如果您希望列表在发现数字之间的 space 时自动放置一个逗号,请使用:
query=input("enter a bunch of numbers: ")
a_list = list(map(int,query.split()))
print(a_list)
*split() 将用逗号分隔它们,无需输入
*例如。 1 2 3 4 5 = [1, 2, 3, 4, 5]
有没有办法请求用户输入并将他们的输入转换为列表、元组或字符串?我想要将一系列数字插入到矩阵中。我可以告诉他们在控制台中输入所有数字,不要有空格,然后遍历它们,但是还有其他方法可以做到这一点吗?
您可以简单地进行如下操作:
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]
NumPy 支持 MATLAB 风格的矩阵定义,如果您正在使用的话:
import numpy as np
s = raw_input('Enter the matrix:')
matrix = np.matrix(s)
例如
Enter the matrix:1 2 3; 4 5 3
将 matrix
设置为:
matrix([[1, 2, 3],
[4, 5, 3]])
每行的条目用空格分隔,行的条目用分号分隔。
如果您希望列表在发现数字之间的 space 时自动放置一个逗号,请使用:
query=input("enter a bunch of numbers: ")
a_list = list(map(int,query.split()))
print(a_list)
*split() 将用逗号分隔它们,无需输入
*例如。 1 2 3 4 5 = [1, 2, 3, 4, 5]