[英]Convert a string into a list with integers including negative numbers
I want to convert this string 我想转换这个字符串
-1, -2, 3, 4, 5
into a list with those values. 包含这些值的列表。
[-1, -2, 3, 4, 5]
When the values are positive, I have many options but I can't seem to get it once there is a "-" character involved. 当值是正数时,我有很多选择,但是一旦涉及到“-”字符,我似乎就无法获得它。
If possible, I'd like not to use regex. 如果可能的话,我不想使用正则表达式。
string = "-1, -2, 3, 4, 5"
print [int(el) for el in string.split(',')]
output: 输出:
[-1, -2, 3, 4, 5]
您可以直接拆分它,然后使用map函数将它们转换为int,如下所示:
arr = map(int,s.strip().split(','))
Simple: 简单:
s = '-1, -2, 3, 4, 5'
lst = [int(x.strip()) for x in s.split(',')]
For the sake of completness of this problem, here is a solution using ast.literal_eval 为了解决此问题,以下是使用ast.literal_eval的解决方案
>>> import ast
>>> list(ast.literal_eval("-1, -2, 3, 4, 5"))
[-1, -2, 3, 4, 5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.