【问题标题】:How do I get my list to read certain values?如何让我的列表读取某些值?
【发布时间】:2022-01-08 04:15:39
【问题描述】:

我是 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)

【问题讨论】:

  • 您的缩进看起来不对——不清楚是否存在复制+粘贴错误,或者这是否是您遇到问题的根源。请查看并编辑您的问题以包含您正在运行的确切代码您收到的确切错误。
  • 我已经编辑了代码x
  • 现在没有足够的代码来运行——不清楚scoresvalues 是什么。而且你还没有包括你的错误。 :(
  • 等一下,我的坏事我把它修好

标签: python list function split python-3.5


【解决方案1】:

这段代码看起来有问题:

    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}")

【讨论】:

  • 非常感谢!!!!!!
猜你喜欢
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
相关资源
最近更新 更多