我正在读取具有列表的文件。以下是输入文件。
[1,2,3,4]
[42]
[1,1,2,3,5,8]
[]
现在,如您所见,有一些列表被读为字符串字符,我正在尝试将其转换为实际列表。下面是我正在使用的代码。
_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。这不是我想要的。
我的代码生成以下结果。
[1, 2, 3, 4]
[4, 2] <--- FALSE
[1, 1, 2, 3, 5, 8]
[]
在不使用诸如以下库的情况下,我应该怎么做才能完成此任务 ast
我会去掉结尾,并用逗号分开。
def str_to_list(s):
return [int(i) for i in s.strip('][').split(',') if i]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句