我想阅读每行中用逗号分隔的数字的文本文件列表,例如:
2,1,3
3,1,3
2,9
并且想要将其转换为列表列表。我当前的功能如下:
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
当前,输出中的数字是字符串:
[['2', '1', '3'], ['3', '1', '3'], ['2', '9']]
但是我希望它们改为数字:
[[2, 1, 3], [3, 1, 3], [2, 9]]
我该如何更改我的功能?
修改此行
line = [int(i) for i in x]
[您还应该知道python随附csv.reader,它已经可以读取以逗号分隔的文本文件。如果要出于线性代数目的而读入2D数组,numpy也是如此。
使用numpy功能将str
转换为int
: