【问题标题】:File iteration. Can't use float object in for loop文件迭代。不能在 for 循环中使用浮点对象
【发布时间】:2018-05-07 13:44:48
【问题描述】:
 def main():
        printIntro() # prints into for user
        diveline = processDives() # calls function to read a file
    
    
    def printIntro():
        print("Welcome to the Diver Scoring program. This program will calculate an \n overall score for a diver, based on individual dives.")
        #prints intro for user
    
    def processDives():
        file_object = open("DiveData.txt", 'r') #opens desired file in read mode
        diveline = file_object.readlines() #reads the line of the file and develops it into a string
        for line in diveline: #iterates through each line in diveline
            calculateDiveScore(line) # calls function to find calculations for dive scores
        print("\nThe average score for these dives is") #prints the average for scores
            
    
    def calculateDiveScore(diveline):
        diveline = diveline.split()
        diveNum = int(diveline[0]) #defines variable for dive number for each dive
        difficulty = float(diveline[1]) #defines variable for difficulty for each dive
        scoreList = diveline[2:] # defines variables to create score list for each dive
        scoreList.remove(max(scoreList)) #removes max value from scoreList
        scoreList.remove(min(scoreList)) #removes min value from scoreList
        sumscoreList = sum(float(i) for i in scoreList) # finds the sum of scoreList
        finalScore = (sumscoreList * difficulty) *.6 # multiplies difficulty and .6 to find the final value for the diver's scores
        print("\nThe diver's score for dive", diveNum, "is", "{0:.2f}".format(finalScore)) # outputs info for user to see which dive has which score
        for i in finalScore:
print(sum(i))

           
    main() #calls main to operate first

此程序遍历文本文件中的数值以查找多次潜水的分数。我试图找到所有潜水的平均分数。我试图找到平均值的值由变量“finalScore”表示。我尝试遍历 for 循环中的值,但是我收到一个类型错误,指出浮点对象不可迭代。我如何才能在 finalScore 下找到这些值的总和和平均值?

这是我用于此程序的文本文件的内容。

1 3.5 5.5 6.0 7.0 6.5 6.5 5.5 7.5

2 2.0 8.0 8.5 8.5 9.0 8.0 8.5 8.0

【问题讨论】:

  • 如果我没记错的话,你的finalScore 似乎是一个标量而不是一个列表,你应该如何遍历它?
  • 如果我无法遍历 finalScore 的值,我还能如何找到它所代表的值的总和?
  • 将上面的代码简单地编辑到导致问题的小循环可能会有所帮助。在 StackOverflow 上,您需要最小的可行代码,我们不需要通读 printIntro、main() 等。与仅将整个脚本粘贴进去相比,更有可能有人会帮助您。
  • 我希望有人自己测试代码,以更好地理解我遇到的问题。
  • finakScorefloat 不是列表。你不能迭代一个浮点数。

标签: python file sum average


【解决方案1】:
sumscoreList = sum(float(i) for i in scoreList)

这里,sum() 不会创建可迭代对象。它只是简单地总结提供给它的值并返回一个。该名称也具有误导性,因为它暗示该变量是一个列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    相关资源
    最近更新 更多