我试图在python代码中使用raw_input来获取列表的用户输入,如下所示.
input_array.append(list(raw_input()));
Run Code Online (Sandbox Code Playgroud)
用户输入为:
1 2 3 5 100
Run Code Online (Sandbox Code Playgroud)
但是代码将输入解释为
[['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']]
Run Code Online (Sandbox Code Playgroud)
尝试:如果我使用plain input()而不是raw_input(),我在控制台中遇到问题.
"SyntaxError: ('invalid syntax', ('<string>', 1, 3, '1 2 3 4 100'))"
Run Code Online (Sandbox Code Playgroud)
注意:我不允许以列表格式提供输入
[1,2,3,5,100]
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何进一步.
>>> [int(x) for x in raw_input().split()]
1 2 3 5 100
[1, 2, 3, 5, 100]
Run Code Online (Sandbox Code Playgroud)
>>> raw_input().split()
1 2 3 5 100
['1', '2', '3', '5', '100']
Run Code Online (Sandbox Code Playgroud)
创建一个按空格分割的新列表然后
[int(x) for x in raw_input().split()]
Run Code Online (Sandbox Code Playgroud)
将此新列表中的每个字符串转换为整数.
list()
Run Code Online (Sandbox Code Playgroud)
是一个从迭代构造列表的函数,例如
>>> list({1, 2, 3}) # constructs list from a set {1, 2, 3}
[1, 2, 3]
>>> list('123') # constructs list from a string
['1', '2', '3']
>>> list((1, 2, 3))
[1, 2, 3] # constructs list from a tuple
Run Code Online (Sandbox Code Playgroud)
所以
>>> list('1 2 3 5 100')
['1', ' ', '2', ' ', '3', ' ', '5', ' ', '1', '0', '0']
Run Code Online (Sandbox Code Playgroud)
也有效,该list函数遍历字符串并将每个字符附加到新列表.但是,您需要使用空格分隔,因此该list功能不适用.
input 获取一个字符串并将其转换为一个对象
'1 2 3 5 100'
Run Code Online (Sandbox Code Playgroud)
不是有效的python对象,它是由空格分隔的5个数字.为清楚起见,请考虑输入
>>> 1 2 3 5 100
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
进入Python Shell.它只是无效的语法.所以也input提出了这个错误.
重要的一点input是:使用
它不是一个安全的功能,即使'[1,2,3,5,100]'你提到的字符串是你不应该使用的,input因为有害的python代码可以通过执行input.如果出现这种情况,请使用ast.literal_eval:
>>> import ast
>>> ast.literal_eval('[1,2,3,5,100]')
[1, 2, 3, 5, 100]
Run Code Online (Sandbox Code Playgroud)