简体   繁体   English

如何将带有逗号的数字的字符串列表转换为 python 中的 integer 列表

[英]How do i convert a string list with numbers with commas to an integer list in python

How do i convert this to a list of integer in python?如何将其转换为 python 中的 integer 列表?

my code:我的代码:

lst = input("Kindly input a string")

[int(element) for element in lst]

I keep getting我不断得到

ValueError: invalid literal for int() with base 10: '[' ValueError: int() 以 10 为底的无效文字:'['

Assuming you are entering string inputs like:假设您正在输入字符串输入,例如:

"[1, 2, 3]"

you may use ast.literal_eval :你可以使用ast.literal_eval

import ast
inp = "[1, 2, 3]"
lst = ast.literal_eval(inp)
print(lst)  # [1, 2, 3]

Or, you could use re.findall :或者,您可以使用re.findall

inp = "[1, 2, 3]"
lst = [int(x) for x in re.findall(r'\d+', inp)]
print(lst)  # [1, 2, 3]

You can use python eval:您可以使用 python 评估:

eval("[1, 2, 3]")
# [1, 2, 3]

eval("2,4,2 ,2 ,23, 23")
# (2, 4, 2, 2, 23, 23)

exact case would be:确切的情况是:

lst = eval(input("Kindly input a string"))

By string manipulations: remove the square brackets with str.strip , make a list of numbers by splitting the string at each occurrence of ', ' (here for simplicity it is assumed there is always a white space after the , ) and finally cast each string-number to integer.通过字符串操作:用str.strip删除方括号,通过在每次出现', '时拆分字符串来制作一个数字列表(这里为简单起见,假设,之后总是有一个空格),最后转换每个字符串编号为 integer。

s = "[1, 2, 3]"

l = list(map(int, s.strip('][').split(', ')))
print(l)

More complex situation,for example when the presence of the white space is not sure it can be solved with a for -loop approach or with regular expression.更复杂的情况,例如,当不确定是否存在空白时,可以使用for循环方法或正则表达式来解决。 For nested list then ast.literal_eval is the choice.对于嵌套列表,那么ast.literal_eval选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM