[英]Converting numbers from text file to Python numbers
我想读取每行中以逗号分隔的数字的文本文件列表,例如:
2,1,3
3,1,3
2,9
并希望将其转换为列表列表。 我当前的 function 看起来像这样:
def nested_int_list_from_file(file):
f = open(file)
xs = []
for line in f :
if not line.strip():
continue
else:
x = line.strip().split(', ')
line = [(i) for i in x]
xs.append(line)
return xs
目前,output 中的数字是字符串:
[['2', '1', '3'], ['3', '1', '3'], ['2', '9']]
但我希望它们是数字:
[[2, 1, 3], [3, 1, 3], [2, 9]]
我需要如何更改我的 function 才能做到这一点?
修改这一行
line = [int(i) for i in x]
您还应该知道 python 附带csv.reader已经可以读取逗号分隔的文本文件。 如果您想出于线性代数目的读入二维数组, numpy 也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.