我明白了,但我该如何离开:
['99', '88', '77', '66\n', '11', '22', '33', '44\n', '78', '58', '68', '88\n']
到:
[[99, 88, 77, 66], [11, 22, 33, 44], [78, 58, 68, 88]]
这是我用来获取第一个输出的函数:
def class_avg(open_file):
new = []
number = []
for i in open_file:
student = i.split(',')
for grade in student[4:]:
new.append(grade)
return new
这是文件格式:
Smith, Joe,9911991199,smithjoe9,99,88,77,66
Ash, Wood,9912334456,ashwood,11,22,33,44
Full, Kare,9913243567,fullkare,78,58,68,88
请您参考如下方法:
首先,您应该如何处理文件以避免出现问题:
def class_avg(open_file):
new = []
for line in open_file:
student = line.strip().split(',')
new.append(list(map(int, student[4:])))
return new
正如@Jean-FrançoisFabre 指出的那样,如果要转换为 int,.strip 并不是必需的,因为它处理空白。你真的可以做类似的事情:
return [[int(s) for s in line.split()[4:]] for line in open_file]
或者更好的是,使用 csv 模块:
import csv
with open('path_to_my_file.txt') as f:
reader = csv.reader(f)
data = [[int(x) for x in row[4:]] for row in reader]
