如何将输入列表转换为整数列表?

How to convert input list into an integer list?

我正在解决一个问题,用户将以这种模式给出输入-

[5,10,15,20]

由于这是用户给出的输入,所以它是一个字符串。我想将这些数字转换成整数并将它们存储在列表中。

我尝试使用以下代码 -

import re
mystr=input()
mylist=list(re.split('[ |, |] ',mystr))
print(mylist)

输出为:

['[5,10,15,20]']

为什么 re.split() 不能正确拆分该输入? 我希望输出是用户输入的整数列表。

如果问题重复,我深表歉意。我是 python 和 Whosebug 的新手。

非常感谢。

如果你足够信任用户(前提是he/she是你自己), 可以使用,但要注意:

mylist = eval("[5,10,15,20]")

更安全的解决方案(无错误处理):

mystr = mystr.strip('[')
mystr = mystr.strip(']')
mylist = [int(i) for i in mystr.split(',')]

要将字符串转换为其 python 等价物:

>>> import ast
>>> mystr = '[5,10,15,20]'
>>> x = ast.literal_eval(mystr)
>>> x
[5, 10, 15, 20]

evalast.literal_eval 更通用。但是,ast.literal_eval 使用起来更安全。

文档

来自python online docs

ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

Changed in version 3.2: Now allows bytes and set literals.

与重新合作

让我们稍微修改正则表达式:

>>> mystr = '[5,10,15,20]'
>>> list(re.split('[ |, |]+', mystr))
['[5', '10', '15', '20]']

去除前导和尾随方括号:

>>> list(re.split('[ |, |]+', mystr.strip('[]')))
['5', '10', '15', '20']

上面给了我们一个字符串列表。要将它们转换为整数:

>>> [int(x) for x in re.split('[ |, |]+', mystr.strip('[]'))]
[5, 10, 15, 20]