Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
与python中的项目搏斗_Python_Loops_File Io - Fatal编程技术网

与python中的项目搏斗

与python中的项目搏斗,python,loops,file-io,Python,Loops,File Io,我的任务是制作这个节目。读取tests.txt的程序显示所有分数和平均分数。该程序还必须使用循环 这就是我到目前为止所做的: def main(): scorefile = open('test.txt', 'r') test1 = scorefile.readline() test2 = scorefile.readline() test3 = scorefile.readline() test4 = scorefile.readline() test5

我的任务是制作这个节目。读取
tests.txt
的程序显示所有分数和平均分数。该程序还必须使用循环

这就是我到目前为止所做的:

def main():

   scorefile = open('test.txt', 'r')

   test1 = scorefile.readline()
   test2 = scorefile.readline()
   test3 = scorefile.readline()
   test4 = scorefile.readline()
   test5 = scorefile.readline()

   scorefile.close()

   print(test1, test2, test3, test4, test5)

   total = (test1 + test2 + test3+ test4 + test5) / 5.0

   print('The average test score is:', total)
main()
我已经用这些数字写入了
test.txt
文件:

95
87
79
91
86
print nums, sum(nums)/len(nums)
[95, 87, 79, 91, 86] 87

因此,假设您有以下文件:

95
87
79
91
86
在任何语言中,我们都需要:

  • 打开文件
  • 通过在文件中的所有行上循环读取文件中的值,直到文件耗尽
  • 处理每个值(例如,它们可能需要从字符串转换为int)
  • 将读取的所有值相加,然后除以读取的值数
  • 在Python中,该配方被转换为:

    nums=list()                      # we will hold all the values in a list                           
    with open(fn, 'r') as f:         # open the file and establish an iterator over the lines
        for n in f:                  # iterate over the lines
            nums.append(int(n))      # read a line, convert to int, append to the list
    
    在交互提示下,您可以“打印”NUM:

    >>> nums
    [95, 87, 79, 91, 86]
    
    现在,您可以打印
    nums
    并计算数字的平均值:

    95
    87
    79
    91
    86
    
    print nums, sum(nums)/len(nums)
    [95, 87, 79, 91, 86] 87
    
    如果要以不同方式打印
    nums
    ,请使用join:

    print '\n'.join(map(str, nums))
    

    用Python编写它的一种更为惯用的方法可能是:

    with open(fn, 'r') as f:
        nums=map(int, f)
        print nums, sum(nums)/len(nums)
    
    如果文件太大,无法放入计算机内存,则需要进行完全不同的讨论

    对于大文件,您只需要保持一个运行总数和计数,而不需要将整个文件加载到内存中。在Python中,您可以执行以下操作:

    with open(fn) as f:
        num_sum=0
        for i, s in enumerate(f, 1):
            print s.strip()
            num_sum+=int(s)
    
        print '\n', num_sum/i
    

    因此,假设您有以下文件:

    95
    87
    79
    91
    86
    
    在任何语言中,我们都需要:

  • 打开文件
  • 通过在文件中的所有行上循环读取文件中的值,直到文件耗尽
  • 处理每个值(例如,它们可能需要从字符串转换为int)
  • 将读取的所有值相加,然后除以读取的值数
  • 在Python中,该配方被转换为:

    nums=list()                      # we will hold all the values in a list                           
    with open(fn, 'r') as f:         # open the file and establish an iterator over the lines
        for n in f:                  # iterate over the lines
            nums.append(int(n))      # read a line, convert to int, append to the list
    
    在交互提示下,您可以“打印”NUM:

    >>> nums
    [95, 87, 79, 91, 86]
    
    现在,您可以打印
    nums
    并计算数字的平均值:

    95
    87
    79
    91
    86
    
    print nums, sum(nums)/len(nums)
    [95, 87, 79, 91, 86] 87
    
    如果要以不同方式打印
    nums
    ,请使用join:

    print '\n'.join(map(str, nums))
    

    用Python编写它的一种更为惯用的方法可能是:

    with open(fn, 'r') as f:
        nums=map(int, f)
        print nums, sum(nums)/len(nums)
    
    如果文件太大,无法放入计算机内存,则需要进行完全不同的讨论

    对于大文件,您只需要保持一个运行总数和计数,而不需要将整个文件加载到内存中。在Python中,您可以执行以下操作:

    with open(fn) as f:
        num_sum=0
        for i, s in enumerate(f, 1):
            print s.strip()
            num_sum+=int(s)
    
        print '\n', num_sum/i
    

    我对代码进行了注释,因此您可以逐步了解该过程:

    # first, let's open the file
    # we use with so that it automatically closes
    # after leaving its scope
    with open("test.txt", "r") as readHere:
        # we read the file and split by \n, or new lines
        content = readHere.read().split("\n")
        # store scores here
        scores = []
        # count is the number of scores we have encountered
        count = 0
        # total is the total of the scores we've encountered
        total = 0
        # now, loop through content, which is a list
        for l in content:
            count += 1          # increment the scores seen by one
            total += int(l)     # and increase the total by the number on this line
            scores.append(int(l))   # add to list
        #one the loop has finished, print the result
        print("average is " + str(total/count) + " for " + str(count) + " scores")
        # print the actual scores:
        for score in scores:
            print(score)
    

    我对代码进行了注释,因此您可以逐步了解该过程:

    # first, let's open the file
    # we use with so that it automatically closes
    # after leaving its scope
    with open("test.txt", "r") as readHere:
        # we read the file and split by \n, or new lines
        content = readHere.read().split("\n")
        # store scores here
        scores = []
        # count is the number of scores we have encountered
        count = 0
        # total is the total of the scores we've encountered
        total = 0
        # now, loop through content, which is a list
        for l in content:
            count += 1          # increment the scores seen by one
            total += int(l)     # and increase the total by the number on this line
            scores.append(int(l))   # add to list
        #one the loop has finished, print the result
        print("average is " + str(total/count) + " for " + str(count) + " scores")
        # print the actual scores:
        for score in scores:
            print(score)
    

    一般方法

    def myAssignmentOnLOOPs():
        aScoreFILE = open( "tests.txt", "r" )
        aSumREGISTER = 0
        aLineCOUNTER = 0
        for aLine in aScoreFILE.readlines():   # The Loop:
            aLineCOUNTER += 1                  #     count this line
            aSumREGISTER += int( aLine )       #     sum adds this line, converted to a number
            print aLine                        #     print each line as task states so
        # FINALLY:
        aScoreFILE.close()                     # .close() the file 
        if ( aLineCOUNTER != 0 ):              # If() to avoid DIV!0 error
            print "Finally, the Sum: ", aSumREGISTER
            print "          an Avg: ", aSumREGISTER / aLineCOUNTER
        else:
            print "There were no rows present in file:tests.txt"
    

    一般方法

    def myAssignmentOnLOOPs():
        aScoreFILE = open( "tests.txt", "r" )
        aSumREGISTER = 0
        aLineCOUNTER = 0
        for aLine in aScoreFILE.readlines():   # The Loop:
            aLineCOUNTER += 1                  #     count this line
            aSumREGISTER += int( aLine )       #     sum adds this line, converted to a number
            print aLine                        #     print each line as task states so
        # FINALLY:
        aScoreFILE.close()                     # .close() the file 
        if ( aLineCOUNTER != 0 ):              # If() to avoid DIV!0 error
            print "Finally, the Sum: ", aSumREGISTER
            print "          an Avg: ", aSumREGISTER / aLineCOUNTER
        else:
            print "There were no rows present in file:tests.txt"
    

    欢迎来到StackOverflow!请务必问一个实际的问题,这样我们才能知道具体如何帮助您。默认情况下,值作为字符串存储在局部变量中。您必须将它们转换为float或int才能工作。欢迎使用StackOverflow!请务必问一个实际的问题,这样我们才能知道具体如何帮助您。默认情况下,值作为字符串存储在局部变量中。您必须将它们强制转换为float或int才能工作。