python - 如何修复列表超出范围

标签 python python-3.x

我将这些数据放在一个文本文件中:

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/

相关文章:

python - 如何将答案存储到 numpy 数组中并使用它来创建 Excel 工作表?

python - Pandas_合并两个大数据集

python - OpenCV Python HoughCircles : Circles detected outside of image boundary

python - 导入模块时如何防止内联代码运行?

python - 使用 poplib 删除电子邮件时出现问题

python - 这个 for 循环是如何工作的?

python - 用于特征选择的详尽网格搜索

python - 了解 CTC 的 TF 实现如何工作

python - 感叹号在表示对象时意味着什么

python - 如何在 openpyxl 中应用条件格式?