我将这些数据放在一个文本文件中:
A, 2, 1500
B, 5, 2000
C, 8, 2500
D, 10, 4000
E, 12, 4800
F, 18, 5300
我有这个程序,它打印超出范围的错误列表:
def readfile(fname):
txt = open(fname)
txt1 = txt.read()
new_list = []
for i in txt1:
split = i.split(', ')
new_list.append({'Car': split[0], 'Seat': int(split[1]), 'cost': int(split[2])})
readfile('car.txt')
任何建议以及如何解决它......谢谢
最佳答案
错误的实际原因是您调用了 text.read()
(当您应该调用 text.readlines()
时)。然后您最终迭代每个字符!
在创建字典并将其附加到列表之前,您可以使用 if
检查来测试行的内容。
def readfile(fname):
c = ['Car', 'Seat', 'Cost']
new_list = []
with open(fname) as f:
for line in f:
if line.strip():
new_list.append(dict(zip(c, i.split(', '))))
return new_list
其他的挑剔 -
- 打开文件时使用
with...as
,这样您就不必调用file.close
dict
+zip
将避免对列表索引进行硬编码。
关于python - 如何修复列表超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46956442/