我是python的初學者。我有一個代碼可以從我的計算機讀取文本檔案并將所有文本轉換為 int。我在分析高爾夫得分功能的最后幾行中苦苦掙扎。
我需要告訴代碼,對于低于 280 的分數,要采用這些值并獲得數量,我知道使用 Len(score) 來獲取數量,但我首先獲取這些值時出錯了。它應該列印低于 180 的分數數,但我不斷收到錯誤,我很迷茫!任何幫助表示贊賞!非常感謝!!!
我的錯誤出現在最后六行代碼中!我不知道如何讓它讀取串列中 280 以下的值:(
錯誤是:
TypeError: '<' not supported between instances of 'str' and 'int'##
在線上:
if score < 280:
def open_and_read_golf_scores():
raw_scores = open("golfscores.txt", "r")
scores = []
for current_line in raw_scores:
values = current_line.split(",")
scores.append(values[2])
raw_scores.close()
return scores
def analyze_golf_scores():
scores = open_and_read_golf_scores()
total = 0
for score in scores:
score = score[0:3]
total = total int(score)
ave = total/len(score)
print("Average score =", ave)
for score in scores:
if score < 280:
scores.append(values)
below_par = total len(score)
print("The number of scores below par is ", below_par)
uj5u.com熱心網友回復:
這段代碼看起來有問題:
for score in scores:
score = score[0:3]
total = total int(score)
ave = total/len(score)
print("Average score =", ave)
for score in scores:
if score < 280:
scores.append(values)
below_par = total len(score)
print("The number of scores below par is ", below_par)
- 您計算
ave的不是分數的數字平均值,而是總分除以每個分數的位數(3)。這就是你要計算的嗎?你的意思是除以len(scores)代替嗎? - 你
scores是字串,你試圖將它們與數字進行比較280,這就是為什么你得到那個TypeError。您應該int像上面那樣將它們轉換為,或者更好的是,首先將open_and_read_golf_scores它們回傳ints。 - 在您遇到該錯誤之后,您嘗試使用 做一些事情
values,這在此范圍內是未系結的。也許你打算使用score?
如果您的open_and_read_golf_scores函式只將分數作為整數回傳,很多問題可能會消失:
from typing import List
def open_and_read_golf_scores() -> List[int]:
with open("golfscores.txt", "r") as raw_scores:
return [
int(current_line.split(",")[2][:3])
for current_line in raw_scores
]
注意:我保留了將每個score字符切成前三個字符的邏輯,但我不知道為什么有必要這樣做,因為我看不到檔案的內容——感覺它實際上可能會導致錯誤。每個分數是否真的恰好是三位數字,并帶有適當的零填充?比分后有什么額外的東西嗎?那是什么東西?有沒有比假設數字總是 3 位長的更安全的方法來擺脫它?
現在您的analyze_golf_scores函式可以簡單得多,因為您可以進行基本的數學運算,scores而無需在回圈中轉換每個專案:
from statistics import mean
def analyze_golf_scores() -> None:
scores = open_and_read_golf_scores()
ave = mean(scores)
below_par = sum(score < 280 for score in scores)
print(f"Average score = {ave}")
print(f"The number of scores below par is {below_par}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370828.html
標籤:Python 列表 功能 分裂 python-3.5
下一篇:如何根據數字撰寫階乘?
