获取用户输入的数字列表
我尝试使用 input
(Py3) /raw_input()
(Py2) 来获取数字列表,但是使用代码
numbers = input()
print(len(numbers))
输入 [1,2, 3]
和 1 2 3
分别给出 7
和 5
的结果 - 它似乎将输入解释为好像一个字符串。有什么直接的方法可以列出它吗?也许我可以使用 re.findall 来提取整数,但如果可能的话,我更愿意使用更 Pythonic 的解决方案。
I tried to use input
(Py3) /raw_input()
(Py2) to get a list of numbers, however with the code
numbers = input()
print(len(numbers))
the input [1,2,3]
and 1 2 3
gives a result of 7
and 5
respectively – it seems to interpret the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use re.findall
to extract the integers, but if possible, I would prefer to use a more Pythonic solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
在 Python 3.x 中,使用它。
例子
In Python 3.x, use this.
Example
解析由空格分隔的数字列表比尝试解析 Python 语法要容易得多:
Python 3:
Python 2:
It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:
Python 3:
Python 2:
使用类似 Python 的语法
标准库提供
ast.literal_eval< /code>
,它可以评估某些字符串,就像它们是 Python 代码一样。这不会造成安全风险,但仍然可能导致崩溃和各种异常。
例如:在我的机器上
ast.literal_eval('['*1000 + ']'*1000)
将引发MemoryError
,即使输入只有 2 KB 的文本。正如文档中所解释的:
(该文档稍微不准确。
ast.literal_eval
还支持数字的加法和减法< /a> - 但不任何其他运算符 - 以便它可以支持复数。)这足以读取和解析格式类似于 Python 代码的整数列表(例如,如果输入是
[1, 2, 3]
例如:切勿将
eval
用于可能全部或部分来自程序外部的输入。安全风险使该输入的创建者能够在没有丰富的专业知识和大量限制的情况下无法正确地沙箱化 - 此时使用ast.literal_eval显然要容易得多。 。
在 Python 2.x 中,
raw_input
相当于 Python 3.xinput
; code>input() 相当于eval(raw_input())
。因此,Python 2.x 在其内置的、专为初学者设计的功能中暴露了一个严重的安全风险,并且这种情况持续了很多年。自 2020 年 1 月 1 日起,它也没有得到正式支持。它大约和 Windows 7 一样过时。除非绝对必要,否则不要使用 Python 2.x;如果这样做,请不要使用内置的
输入
。使用您自己的语法
当然,显然可以根据自定义规则解析输入。例如,如果我们想要读取整数列表,一种简单的格式是期望整数值由空格分隔。
为了解释这一点,我们需要:
所有这些任务都包含在共同的链接副本中;生成的代码显示在此处的最佳答案中。
使用其他语法
我们可以期望输入采用其他现有的标准格式,例如 JSON、CSV 等,而不是发明输入格式。标准库包含解析这两种格式的工具。然而,期望人们在提示时手动键入此类输入通常不太方便用户。通常这种输入将从文件中读取。
验证输入
ast.literal_eval
还将读取并解析许多不是整数列表的内容;因此,需要整数列表的后续代码仍需要验证输入。除此之外,如果输入的格式不符合预期,通常会抛出某种异常。通常,您需要检查这一点,以便重复提示。请参阅询问用户输入,直到他们给出有效响应。
Using Python-like syntax
The standard library provides
ast.literal_eval
, which can evaluate certain strings as though they were Python code. This does not create a security risk, but it can still result in crashes and a wide variety of exceptions.For example: on my machine
ast.literal_eval('['*1000 + ']'*1000)
will raiseMemoryError
, even though the input is only two kilobytes of text.As explained in the documentation:
(The documentation is slightly inaccurate.
ast.literal_eval
also supports addition and subtraction of numbers - but not any other operators - so that it can support complex numbers.)This is sufficient for reading and parsing a list of integers formatted like Python code (e.g. if the input is
[1, 2, 3]
. For example:Do not ever use
eval
for input that could possibly ever come, in whole or in part, from outside the program. It is a critical security risk that enables the creator of that input to run arbitrary code.It cannot be properly sandboxed without significant expertise and massive restrictions - at which point it is obviously much easier to just use
ast.literal_eval
. This is increasingly important in our Web-connected world.In Python 2.x,
raw_input
is equivalent to Python 3.xinput
; 2.xinput()
is equivalent toeval(raw_input())
. Python 2.x thus exposed a critical security risk in its built-in, designed-to-be-beginner-friedly functionality, and did so for many years. It also has not been officially supported since Jan 1, 2020. It is approximately as outdated as Windows 7.Do not use Python 2.x unless you absolutely have to; if you do, do not use the built-in
input
.Using your own syntax
Of course, it is clearly possible to parse the input according to custom rules. For example, if we want to read a list of integers, one simple format is to expect the integer values separated by whitespace.
To interpret that, we need to:
All of those tasks are covered by the common linked duplicates; the resulting code is shown in the top answer here.
Using other syntaxes
Rather than inventing a format for the input, we could expect input in some other existing, standard format - such as JSON, CSV etc. The standard library includes tools to parse those two. However, it's generally not very user-friendly to expect people to type such input by hand at a prompt. Normally this kind of input will be read from a file instead.
Verifying input
ast.literal_eval
will also read and parse many things that aren't a list of integers; so subsequent code that expects a list of integers will still need to verify the input.Aside from that, if the input isn't formatted as expected, generally some kind of exception will be thrown. Generally you will want to check for this, in order to repeat the prompt. Please see Asking the user for input until they give a valid response.
您可以使用
.split()
这仍然会为您提供字符串,但它将是一个字符串列表。
如果您需要将它们映射到类型,请使用列表理解:
如果您希望能够输入任何 Python 类型并自动映射它并且您信任您的用户隐式那么你可以使用
eval
< /a>You can use
.split()
This will still give you strings, but it will be a list of strings.
If you need to map them to a type, use list comprehension:
If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use
eval
另一种方法是使用 for 循环。
假设您希望用户在名为“memo”的列表中输入 10 个数字
Another way could be to use the for-loop for this one.
Let's say you want user to input 10 numbers into a list named "memo"
您可以将列表的字符串表示形式传递给 json:
用户像在 python 中一样输入列表:
[2, 34, 5.6, 90]
you can pass a string representation of the list to json:
user enters in the list as you would in python:
[2, 34, 5.6, 90]
答案很简单。试试这个。
x=input()
假设
[1,3,5,'aA','8as']
作为输入给出print len(x)< /code>
这给出了答案 5
print x[3]
这给出了
'aA'
Answer is trivial. try this.
x=input()
Suppose that
[1,3,5,'aA','8as']
are given as the inputsprint len(x)
this gives an answer of 5
print x[3]
this gives
'aA'
上面的代码片段是从用户获取值的简单方法。
The above code snippets is easy method to get values from the user.
获取用户输入的号码列表。
这可以通过使用python中的list来完成。
这里L表示列表,map用于将输入与位置进行映射,int 指定用户输入的数据类型,为整数数据类型,split()用于根据空格分割数字。
。
Get a list of number as input from the user.
This can be done by using list in python.
Here L indicates list, map is used to map input with the position, int specifies the datatype of the user input which is in integer datatype, and split() is used to split the number based on space.
.
我想如果你不使用第一个答案中提到的 split() 就可以做到这一点。它将适用于所有不带空格的值。因此,您不必像第一个答案中那样给出空格,我想这更方便。
这是我的输出:
I think if you do it without the split() as mentioned in the first answer. It will work for all the values without spaces. So you don't have to give spaces as in the first answer which is more convenient I guess.
Here is my ouput:
试试这个,
如果列表的元素只是一个数字,则语句 1 将被执行,如果它是一个字符串,则将执行语句 2。最后你将得到一个你需要的列表 l1 。
try this one ,
If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.