为什么列表中没有填充此代码?

时间:2014-11-14 04:51:21

标签: python list while-loop

我为类编写了这段代码,无法弄清楚为什么我的列表没有填充任何值。我尝试过使用调试器但仍然无法弄清楚它为何无法正常工作。有任何想法吗?另外......我知道循环会更有意义,但我需要使用while循环来进行赋值。

__author__ = 'Ethan'
#This program reads in a file from the user which contains lines of

def mileage():
    filename = input("Please enter the file name: ")
    file = open(filename,"r")
    line_list = []
    num_lines = sum(1 for line in file)
    line_counter = 0

    while line_counter <= num_lines:
        line = file.readline()
        line_items = line.split()
        line_list.append(line_items)
        line_counter += 1

    current_index_pos = 0

    while current_index_pos <= num_lines:
        current_item = line_list[current_index_pos]
        print("Leg",current_index_pos + 1,"---", current_item[0]/current_item[1],"miles/gallon")
        current_index_pos += 1
mileage()

1 个答案:

答案 0 :(得分:4)

这将读到文件的末尾

num_lines = sum(1 for line in file)

所以当你到达这里时,没有任何行可供阅读

    line = file.readline()

最好像这样构建代码

with open(filename, "r") as fin:
    for line_counter, line in enumerate(fin):
        line_items = line.split()
        line_list.append(line_items)
    # after the loop line_counter has counted the lines

甚至(如果你不需要line_counter)

with open(filename, "r") as fin:
    line_list = [line.split() for line in fin]

更高级的是使用生成器表达式或在单个循环中执行所有操作以避免需要立即将整个文件读入内存

def mileage():
    filename = input("Please enter the file name: ")

    with open(filename, "r") as fin:
        for line_counter, line in enumerate(fin):
            current_item = line.split()
            print("Leg",line_counter + 1,"---", float(current_item[0])/float(current_item[1]),"miles/gallon")