我得到了这个,但我该怎么做呢:
['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
答案 0 :(得分:5)
以下是您应该如何阅读处理文件以避免问题:
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指出,如果你要转换为.strip
,因为它处理空格,int
并不是必需的。你真的可以这样做:
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]
答案 1 :(得分:1)
尝试这样的事情
output = []
sub_l = []
for i in your_input:
if "\n" in i:
sub_l.append(int(i.replace("\n","")))
output.append(sub_l)
sub_l=[]
else:
sub_l.append(int(i))
print(output)
答案 2 :(得分:0)
如果你喜欢迭代技巧......
enctype
答案 3 :(得分:0)
l=['99', '88', '77', '66\n', '11', '22', '33', '44\n', '78', '58', '68', '88\n']
y=[]
z=[]
for x in l:
y.append(int(x))
if '\n' in x:
z.append(y)
y=[]
print (z)
输出
[[99, 88, 77, 66], [11, 22, 33, 44], [78, 58, 68, 88]]
答案 4 :(得分:0)
尝试此功能:如果要更改子列表的长度,可以更改步进器。
def list_divider(ls,stepper=4):
#Get rid of the \n.
ls=list(map(str.strip,ls))
result=[]
pos = 0
#Slice the list by moving pos 4 steps each time
while pos<=len(ls)-1:
result.append(ls[pos:pos+stepper])
pos+=stepper
return result
我希望这很有帮助
答案 5 :(得分:0)
这是一个相当简洁的方法,使用csv
模块读取文件,itertools
模块重新格式化数据以进行计算。
import csv
import itertools
def class_avg(open_file):
grades = tuple(itertools.chain.from_iterable( # Put all grades into single sequence.
itertools.chain(map(int, row[4:]) # Convert grades in row to integers.
for row in csv.reader(open_file))))
total = sum(grades)
return total / len(grades)
with open('class_grades.txt', newline='') as file:
print(class_avg(file)) # -> 61.0
打印的值适用于您问题中示例文件中的值。