【问题标题】:Attribute Error While Trying to Run Insertion Sort尝试运行插入排序时出现属性错误
【发布时间】:2022-12-09 20:42:35
【问题描述】:

我目前正在创建一个乌龟游戏,它将在一系列记录中收集分数和首字母,我想运行插入排序以便向用户显示他们是否收到了前三名之一。但是,每当我尝试运行代码时,我都会收到一个属性错误。代码在这里(如果需要可以提供更多代码):

def insertion_sort(scores):
  value = 0
  i=0
  for i in range(1, len(scores)):
    value = scores[i].Score
    j = i - 1
    while j>= 0 and scores[j].Score > value:
      scores[j + 1].Score = scores[j].Score
      j -=1
    scores[j + 1].Score = value
  return scores

我曾尝试重新排列我的数据并更改数据的存储方式,但没有任何帮助。我不确定还有什么可以尝试,因为我已经尝试过几种不同的解决方案,但都没有成功。

【问题讨论】:

  • AttributeError: 'int' 对象没有属性 'Score'?
  • 您代码中的哪一行抛出错误?
  • “1”是优化吗?

标签: python arrays record insertion-sort


【解决方案1】:

您看到的错误 AttributeError: 'int' object has no attribute 'Score' 表示您正在尝试访问不具有此属性的对象的 Score 属性。在您的代码中,您试图访问分数列表中元素的 Score 属性,但这些元素不是具有 Score 属性的对象。

要修复此错误,您需要更改分数列表中的元素,使它们成为具有 Score 属性的对象。这可以通过创建一个具有 Score 属性的自定义类,然后创建此类的实例以存储在分数列表中来完成。

喜欢;

class Record:
  def __init__(self, score):
    self.Score = score

def insertion_sort(scores):
  value = 0
  i=0
  for i in range(1, len(scores)):
    value = scores[i].Score
    j = i - 1
    while j>= 0 and scores[j].Score > value:
      scores[j + 1].Score = scores[j].Score
      j -=1
    scores[j + 1].Score = value
  return scores

# Create a list of Record objects with the scores
scores = [Record(10), Record(5), Record(15)]

# Sort the list of scores using insertion sort
scores = insertion_sort(scores)

# Print the sorted list of scores
for score in

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 2017-10-17
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多