![](/img/trans.png)
[英]Converting elements of list of nested lists from string to integer in python
[英]converting string to integer in nested list - python
我是 python 的新手。
我试图得到[[7, 1], [8], [4, 0, 5]]
这个结果,但我不断得到[['7, 1'], ['8'], ['4, 0, 5']]
。
def nested_list(f):
opener = open(f,"r")
lst =[lin.strip().split(" , ") for lin in opener]
return lst
如何更正我的代码?
您需要将其从string
转换为int
。 一种方法是使用map
def nested_list(f):
opener = open(f,"r")
lst = [map(int, lin.strip().split(" , ")) for lin in opener]
return lst
如果您的问题准确地代表了该文件,则它如下所示,逗号后加一个空格:
7, 1
8
4, 0, 5
用这个:
def nested_list(f):
with open(f) as opener: # so the file is closed automatically.
return [[int(x) for x in lin.strip().split(', ')] for lin in opener]
代替int您可以在上述两个答案中使用eval function。当您的字符串包含特殊字符而 eval 工作顺利时,Int function 会给出错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.