我在某处错过了打印命令吗?

时间:2017-10-23 23:22:34

标签: python file for-loop

我的任务是制作一个程序,从文件中读取数字,然后显示这些数字的平均值。所以:

def main ():
    #open the file numbers.txt, this file is located in the IDLE directory
    #on my flash drive.
    numbers_file = open(r'{file path}\numbers.txt', 'r')
    number_total = 0
    #read each line of the file, numbers.txt
    line = numbers_file.readline()
    #declare a line counter, this will be needed to determine the average of
    #all the numbers in the file
    line_number = 1
    #check that the line is valid, as long as an emptry string is not
    #returned, continue
    while line != '':
        #convert the line to a float
        number_entry = float(line)
        #count what line that was
        line_number += 1
        #add the current number in the line to the total of the lines so far
        number_total += number_entry
    #when the last line is read,
    file_average = number_total/line+number
    numbers_file.close()
    print(file_average)

#call the main function
main ()

我跑了......等我......等等等等......

numbers.txt只有10个数字;这应该在一瞬间完成。我错过了什么?

3 个答案:

答案 0 :(得分:5)

您正在阅读第一行

while line != '':
    number_entry = float(line)
    line_number += 1
    number_total += number_entry

    #read the next line
    line = numbers_file.readline()

然后在您的line = numbers_file.readline() 循环中,您希望while的值可以更改。这将要求您在循环中也调用line方法。但是你有一个更加pythonic选项,利用readline对象实现file接口的事实。

删除iterator并将line = numbers_file.readline()循环更改为:

while line != '':

答案 1 :(得分:2)

在循环内没有变化,并且没有中断;一旦你进入循环,你就会卡住。我希望你需要的是在循环中移动(或复制) readline

public interface IListAllMarkets
{
    List<Market> GetAllMarkets();
}
public interface IListMarketPrice
{
    List<MarketPrice> GetMarketPrices();
}
public interface IListOrders
{
    List<Order> GetOrders();
}
public interface IHighLow
{
    List<HighLow> GetHighLows();
}

// then the class that handles the apis

public class MyReusableClass :  IListAllMarkets, 
                                IListMarketPrice, 
                                IListOrders, 
                                IHighLow
{
    private readonly ApiA _apiA = new ApiA();
    private readonly ApiB _apiB = new ApiB();

    public List<Market> GetAllMarkets()
    {
        return _apiA.ListAllMarkets() ;
    }

    public List<MarketPrice> GetMarketPrices()
    {
        // pretending that the business logic is try apiA first then fallback to apiB
        var prices = _apiA.ListSpecificMarketPrices();
        if (prices.Count == 0)
        {
            prices = _apiB.ListSpecificMarketPrices();
        }
        return prices;
    }

    public List<Order> GetOrders()
    {
        return _apiA.ListAllOrders();
    }

    public List<HighLow> GetHighLows()
    {
        return _apiB.ListMarket24HourJHighsLows();
    }
}

答案 2 :(得分:0)

 file_average = number_total/line+number

在while循环之后,您使用line来达到平均值。这是真的需要吗?或者您是否找到了每条线的平均值然后放入while循环。