[英]converting a single integer number input to a list in python
I am looking for a single line command in python to convert an integer input to list. 我正在寻找Python中的单行命令将整数输入转换为列表。 The following is the situation.
以下是情况。
mylist=[]
mylist=list(input('Enter the numbers: '))
The above line works perfectly if i give more than one number as input. 如果我给多个输入作为输入,则以上行可以完美地工作。 Eg 1,2,3 .
例如1,2,3。 But it gives Error when i give only a single digit entry.
但是当我只输入一个数字时,就会出现错误。 Eg: 1 .
例如:1。 Saying it cannot convert an integer to list.
说它不能将整数转换为列表。 I don't want to run a loop asking user for each input.
我不想运行一个循环,要求用户输入每个输入。 So i want a one line command which will work for one or more digits input given by user separated by commas.
所以我想要一个单行命令,该命令适用于用户输入的一个或多个数字,用逗号分隔。
Thanking you, -indiajoe 谢谢你-indiajoe
You should use raw_input
and convert to int
with a list comprehension: 您应该使用
raw_input
并通过列表理解将其转换为int
:
user_input = raw_input('Enter the numbers: ')
my_list = [int(i) for i in user_input.split(',')]
From the offical documentation : raw_input
reads a line from input, converts it to a string (stripping a trailing newline), and returns that. 从官方文档中 :
raw_input
从输入中读取一行,将其转换为字符串(带末尾的换行符),然后将其返回。
I think that the simplest thing that you can do is: 我认为您可以做的最简单的事情是:
mylist = map(int, raw_input('Enter the numbers: ').split(','))
But it's nearly the same that using a list comprehension. 但是,使用列表理解几乎相同。
input
eval()
's what you type. input
eval()
就是您输入的内容。 So, when you type 1,2,3
, the result is a tuple
; 因此,当您键入
1,2,3
,结果是一个tuple
; when you type 1
, the result is an int
. 当您键入
1
,结果为int
。 Try typing 1,
instead of 1
. 尝试输入
1,
而不是1
。 Note that your first line ( mylist=[]
) is unnecessary. 请注意,您的第一行(
mylist=[]
)是不必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.