Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将整数的输入字符串转换为list,然后转换为int?_Python - Fatal编程技术网

在python中将整数的输入字符串转换为list,然后转换为int?

在python中将整数的输入字符串转换为list,然后转换为int?,python,Python,我希望用户输入一个整数(6位数,所以是123456而不是1),然后将该输入转换为一个列表,[1,2,3,4,5,6] 我试过这个: user_input = list(input("Please enter an 8 digit number") numbers = [int(i) for i in user_input] 我希望能够用数字列表执行数学运算,但我不断得到错误“int是不可数的”。坦率地说,我不完全确定我在做什么,也不确定“数字=[…]”是否有必要,或者它是否应该是numbers

我希望用户输入一个整数(6位数,所以是123456而不是1),然后将该输入转换为一个列表,
[1,2,3,4,5,6]

我试过这个:

user_input = list(input("Please enter an 8 digit number")
numbers = [int(i) for i in user_input]
我希望能够用数字列表执行数学运算,但我不断得到错误“int是不可数的”。坦率地说,我不完全确定我在做什么,也不确定“数字=[…]”是否有必要,或者它是否应该是
numbers=user\u input
。尝试
numbers=[i for i in user\u input]
会得到相同的错误

此外,我意识到我可以运行一个循环从用户那里获取每个数字,或者让他们在每个数字之间使用逗号,以便使用
.split(“,”
),但我不希望这样,因为用户觉得这看起来很混乱

编辑:我一直在不同版本之间切换,所以很抱歉出现任何混乱。这是在2.7中编写的,尽管我打算使用Python 3。

在Python 2.7中,
input()
返回一个整数。要将输入读取为字符串,请使用函数
raw\u input()
。或者,您可以切换到Python 3,其中
input()
始终返回字符串

此外,如果用户提供的数字超过1位数,您的解决方案也不是很整洁。例如,字符串“123”可以解释为[1,2,3]、[12,3]等等

一个简洁的解决方案是要求用户提供由空格分隔的输入,如下x_1,x_2。。。x_n

然后,Python 3.0中的代码将如下所示

lst = [int(x) for x in input().split()]
对于Python2.7

lst = [int(x) for x in raw_input().split()]

函数
input
在Python2和Python3中的行为完全不同

这似乎是Python2。在Python 2中,
input
将输入的数据作为Python代码进行计算。如果只输入数字,
input
将返回一个整数。无法将其转换为列表,因此会出现错误

输入
是不安全的,会导致许多问题,因此最好避免它。使用
原始输入

user_input = raw_input("Please enter an 8 digit number: ")
这将返回一个字符串,例如
'12345678'

可以将其转换为列表。列表将逐个字符遍历字符串

digits = list(user_input)   # e.g. ['1', '2', '3', '4', '5', '6', '7', '8']
但这甚至不是必需的,您可以直接执行以下操作:

numbers = [int(i) for i in user_input]   # e.g. [1, 2, 3, 4, 5, 6, 7, 8]


顺便说一句,Python3版本的
input
与Python2的
raw\u input

相同,您不是在Python2中吗?如果是这样,请使用原始输入而不是输入您的问题在其他地方,而不是您在此处显示的代码中。Python的哪个版本?