3 回答
TA贡献2019条经验 获得超9个赞
以下应该有效:
with open('myfile.csv') as f:
t=f.read()
t=t.replace('\n', '').replace(' ', ' ').replace(' ', ',')
l=t.split(']')
l.pop()
l=[i.replace('[', '') for i in l]
result=[[int(s) for s in k.split(',')] for k in l]
print(result)
输出:
[[12, 34, 45, 22, 3, 5, 34, 33, 2, 67, 5, 55, 2, 90, 88, 12, 34], [245, 4, 13], [33, 90, 50, 22, 90, 1, 23, 44, 876, 10, 7]]
TA贡献1831条经验 获得超9个赞
您可以使用内置csv库,然后只需拆分每行的值:
import csv
with open('test.csv', 'r') as testCsvFile:
testCsv = csv.reader(testCsvFile)
listOfLists = []
for row in testCsv:
listOfLists.append([int(val) for val in row[0][1:-1].split(' ')])
print(listOfLists)
# Output
# [[12, 34, 45, 22, 3, 5, 34, 33, 2, 67, 5, 55, 2, 90, 88, 12, 34], [245, 4, 13], [33, 90, 50, 22, 90, 1, 23, 44, 876, 10, 7]]
编辑:更新了解析以将值转换为ints
TA贡献1812条经验 获得超5个赞
这是你想要的:
>>> with open("file.txt", "r") as f:
... content = f.read().replace("\n", "")
...
>>> content = [[int(i) for i in c.split(" ")] for c in content[1:-1].split("][")]
>>> content
[[12, 34, 45, 22, 3, 5, 34, 33, 2, 67, 5, 55, 2, 90, 88, 12, 34], [245, 4, 13], [33, 90, 50, 22, 90, 1, 23, 44, 876, 10, 7]]
首先将整个文件作为一个字符串读取,去掉第一个和最后一个字符 ([和]) 以及换行符 ( \n)。然后分割成块除以][。最后用空格字符分割每个块并将它们转换为整数。
添加回答
举报