将单个整数输入转换为Python中的列表

发布于 2024-12-28 09:07:41 字数 301 浏览 2 评论 0原文

我正在寻找 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

落在眉间の轻吻 2025-01-04 09:07:41

我认为您可以做的最简单的事情是:

mylist = map(int, raw_input('Enter the numbers: ').split(','))

但这与使用列表理解几乎相同。

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.

计㈡愣 2025-01-04 09:07:41

您应该使用 raw_input 并通过列表理解转换为 int

user_input = raw_input('Enter the numbers: ')
my_list = [int(i) for i in user_input.split(',')]

来自 官方文档raw_input 从输入中读取一行,将其转换为字符串(去除尾随换行符),然后返回。

You should use raw_input and convert to int with a list comprehension:

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.

紫罗兰の梦幻 2025-01-04 09:07:41

input eval() 是您输入的内容。因此,当您输入 1,2,3 时,结果是一个 tuple;当您输入 1 时,结果是 int。尝试输入 1, 而不是 1。请注意,第一行 (mylist=[]) 是不必要的。

input eval()'s what you type. So, when you type 1,2,3, the result is a tuple; when you type 1, the result is an int. Try typing 1, instead of 1. Note that your first line (mylist=[]) is unnecessary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文