将在String中读取的输入列表转换为Python中的列表 [英] Converting Input List that is read in String to List in Python
本文介绍了将在String中读取的输入列表转换为Python中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在读取包含列表的文件.下面是输入文件.
I am reading a file that has list. Below is the input file.
[1,2,3,4]
[42]
[1,1,2,3,5,8]
[]
现在正如您所看到的,有一些列表被读取为字符串字符,我正在尝试将其转换为实际列表.下面是我正在使用的代码.
Now as you can see there are lists which is read as string character and I am trying to convert it into an actual list. Below is the code I'm using.
_list = list(sys.stdin.readline().strip())
_final_list = []
for n in _list:
try:
n = int(n)
except ValueError:
continue
if isinstance(n, int):
_final_list.append(n)
现在我的代码可以正常工作,直到数字超过一位.例如42将变成4、2.这不是我想要的.
Now my code works fine until a number is more than one digit. For example 42 would become 4, 2. Which is not what I want.
我的代码生成以下结果.
My code generates below result.
[1, 2, 3, 4]
[4, 2] <--- FALSE
[1, 1, 2, 3, 5, 8]
[]
在不使用诸如 ast
推荐答案
我会去掉结尾并用逗号分开.
I would strip the endings and split by commas.
def str_to_list(s):
return [int(i) for i in s.strip('][').split(',') if i]
这篇关于将在String中读取的输入列表转换为Python中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文