获取用户输入的数字列表

发布于 2024-10-11 16:18:23 字数 332 浏览 2 评论 0原文

我尝试使用 input (Py3) /raw_input() (Py2) 来获取数字列表,但是使用代码

numbers = input()
print(len(numbers))

输入 [1,2, 3]1 2 3 分别给出 75 的结果 - 它似乎将输入解释为好像一个字符串。有什么直接的方法可以列出它吗?也许我可以使用 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 技术交流群。

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

发布评论

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

评论(11

在风中等你 2024-10-18 16:18:23

在 Python 3.x 中,使用它。

a = [int(x) for x in input().split()]

例子

>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>> 

In Python 3.x, use this.

a = [int(x) for x in input().split()]

Example

>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>> 
很酷不放纵 2024-10-18 16:18:23

解析由空格分隔的数字列表比尝试解析 Python 语法要容易得多:

Python 3:

s = input()
numbers = list(map(int, s.split()))

Python 2:

s = raw_input()
numbers = map(int, s.split())

It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:

Python 3:

s = input()
numbers = list(map(int, s.split()))

Python 2:

s = raw_input()
numbers = map(int, s.split())
给不了的爱 2024-10-18 16:18:23

使用类似 Python 的语法

标准库提供 ast.literal_eval< /code>,它可以评估某些字符串,就像它们是 Python 代码一样。这不会造成安全风险,但仍然可能导致崩溃和各种异常。

例如:在我的机器上 ast.literal_eval('['*1000 + ']'*1000) 将引发 MemoryError,即使输入只有 2 KB 的文本。

正如文档中所解释的:

提供的字符串或节点只能包含以下 Python 文字结构:字符串、字节、数字、元组、列表、字典、集合、布尔值、NoneEllipsis.

(该文档稍微不准确。ast.literal_eval支持数字的加法和减法< /a> - 但任何其他运算符 - 以便它可以支持复数。)

这足以读取和解析格式类似于 Python 代码的整数列表(例如,如果输入是 [1, 2, 3] 例如:

>>> import ast
>>> ast.literal_eval(input("Give me a list: "))
Give me a list: [1,2,3]
[1, 2, 3]

切勿将 eval 用于可能全部或部分来自程序外部的输入。安全风险使该输入的创建者能够

在没有丰富的专业知识和大量限制的情况下无法正确地沙箱化 - 此时使用ast.literal_eval显然要容易得多。 。

在 Python 2.x 中,raw_input 相当于 Python 3.x input; 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 raise MemoryError, even though the input is only two kilobytes of text.

As explained in the documentation:

The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.

(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:

>>> import ast
>>> ast.literal_eval(input("Give me a list: "))
Give me a list: [1,2,3]
[1, 2, 3]

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.x input; 2.x input() is equivalent to eval(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.

千年*琉璃梦 2024-10-18 16:18:23

您可以使用 .split()

numbers = raw_input().split(",")
print len(numbers)

这仍然会为您提供字符串,但它将是一个字符串列表。

如果您需要将它们映射到类型,请使用列表理解:

numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)

如果您希望能够输入任何 Python 类型并自动映射它并且您信任您的用户隐式那么你可以使用eval< /a>

You can use .split()

numbers = raw_input().split(",")
print len(numbers)

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:

numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)

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

怼怹恏 2024-10-18 16:18:23

另一种方法是使用 for 循环。
假设您希望用户在名为“memo”的列表中输入 10 个数字

memo=[] 
for i in range (10):
    x=int(input("enter no. \n")) 
    memo.insert(i,x)
    i+=1
print(memo) 

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"

memo=[] 
for i in range (10):
    x=int(input("enter no. \n")) 
    memo.insert(i,x)
    i+=1
print(memo) 
吝吻 2024-10-18 16:18:23

您可以将列表的字符串表示形式传递给 json:

import json

str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)

用户像在 python 中一样输入列表:[2, 34, 5.6, 90]

you can pass a string representation of the list to json:

import json

str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)

user enters in the list as you would in python: [2, 34, 5.6, 90]

沐歌 2024-10-18 16:18:23

答案很简单。试试这个。

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 inputs

print len(x)

this gives an answer of 5

print x[3]

this gives 'aA'

萧瑟寒风 2024-10-18 16:18:23
a=[]
b=int(input())
for i in range(b):
    c=int(input())
    a.append(c)

上面的代码片段是从用户获取值的简单方法。

a=[]
b=int(input())
for i in range(b):
    c=int(input())
    a.append(c)

The above code snippets is easy method to get values from the user.

时光沙漏 2024-10-18 16:18:23

获取用户输入的号码列表。

这可以通过使用python中的list来完成。

L=list(map(int,input(),split()))

这里L表示列表,ma​​p用于将输入与位置进行映射,int 指定用户输入的数据类型,为整数数据类型,split()用于根据空格分割数字。

输入图片此处描述

Get a list of number as input from the user.

This can be done by using list in python.

L=list(map(int,input(),split()))

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.

.

enter image description here

予囚 2024-10-18 16:18:23

我想如果你不使用第一个答案中提到的 split() 就可以做到这一点。它将适用于所有不带空格的值。因此,您不必像第一个答案中那样给出空格,我想这更方便。

a = [int(x) for x in input()]
a

这是我的输出:

11111
[1, 1, 1, 1, 1]

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.

a = [int(x) for x in input()]
a

Here is my ouput:

11111
[1, 1, 1, 1, 1]
嘿哥们儿 2024-10-18 16:18:23

试试这个,

n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
    a=raw_input()
    if(a.isdigit()):
        l1.insert(i,float(a)) #statement1
    else:
        l1.insert(i,a)        #statement2

如果列表的元素只是一个数字,则语句 1 将被执行,如果它是一个字符串,则将执行语句 2。最后你将得到一个你需要的列表 l1 。

try this one ,

n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
    a=raw_input()
    if(a.isdigit()):
        l1.insert(i,float(a)) #statement1
    else:
        l1.insert(i,a)        #statement2

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.

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