将单个整数输入转换为Python中的列表
我正在寻找 python 中的单行命令来将整数输入转换为列表。 以下是情况。
mylist=[]
mylist=list(input('Enter the numbers: '))
如果我给出多个数字作为输入,上面的行就可以完美地工作。例如 1,2,3 。但当我只输入一位数字时,它会出现错误。例如: 1 。说它无法将整数转换为列表。 我不想运行循环询问用户每个输入。因此,我想要一个单行命令,该命令适用于用户输入的一个或更多数字,并用逗号分隔。
谢谢你, -印第安乔
I am looking for a single line command in python to convert an integer input to list.
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 . But it gives Error when i give only a single digit entry. Eg: 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您可以做的最简单的事情是:
但这与使用列表理解几乎相同。
I think that the simplest thing that you can do is:
But it's nearly the same that using a list comprehension.
您应该使用
raw_input
并通过列表理解转换为int
:来自 官方文档:
raw_input
从输入中读取一行,将其转换为字符串(去除尾随换行符),然后返回。You should use
raw_input
and convert toint
with a list comprehension:From the offical documentation:
raw_input
reads a line from input, converts it to a string (stripping a trailing newline), and returns that.input
eval()
是您输入的内容。因此,当您输入1,2,3
时,结果是一个tuple
;当您输入1
时,结果是int
。尝试输入1,
而不是1
。请注意,第一行 (mylist=[]
) 是不必要的。input
eval()
's what you type. So, when you type1,2,3
, the result is atuple
; when you type1
, the result is anint
. Try typing1,
instead of1
. Note that your first line (mylist=[]
) is unnecessary.