【问题标题】:Using loops to find the highest score, lowest score from a list使用循环从列表中查找最高分、最低分
【发布时间】:2021-01-18 15:21:20
【问题描述】:

更新:我似乎理解错误的代码方向。

对 Python 来说绝对是新人,因此非常感谢任何帮助。

我正在尝试使用循环从数组中找到最高分和最低分。

这是我处理的代码:

nums = [6, 8, 9, 5, 3, 3, 5, 3]
highest_score = []
lowest_score = []

def calculate_Scores(nums):
  i = 1
  max = min = nums[0]
  if nums[0] > nums[1]:
    highest_score.append(nums[0])
  elif nums[0] < nums[1]:
    lowest_score.append(nums[0])
  while i < len(nums):
    if nums[i] > max:
      highest_score.append(nums[i])
    if nums[i] < min:
      lowest_score.append(nums[i])
    i += 1

 calculate_Scores(nums)
 print(highest_score)
 print(lowest_score)

输出:

 [8, 9] #highest
 [6, 5, 3, 3, 5, 3] #lowest

代码对上面给出的数组工作得很好,但是当你将数组 nums 更改为:

[2, 8, 9, 5, 3, 3, 5, 3]

这是输出:

[8, 9, 5, 3, 3, 5, 3] #highest
[2] #lowest

我怎样才能让它工作,以便 3 也进入变量最低分数? 还有其他方法可以使整个过程正常进行吗? (不使用 max() 和 min())

【问题讨论】:

  • 为什么要创建highest_scorelowest_score 列表?为什么不直接将它们设为数字,并在每次获得更大值时替换它们?实际上,您只是根据数字大于还是小于第一个元素对数字进行排序。
  • 确定最高和最低的逻辑是什么?通常有一个值最低,一个值最高。
  • 我明白你的意思。我基本上是从文本文件中读取数字,文本文件包含来自不同团队的分数。在用户输入新分数后,分数将被更新。这是我要遵循的方向:“实际上,您可以使用循环,在循环的每次迭代中,您从文件中读取一个数字,将其与当前的最高/最低分数进行比较并更新最高/最低如果需要。”
  • 根据您分享的说明,听起来最高分和最低分是数字,而不是列表。
  • @GreenCloakGuy 你能详细说明一下吗??

标签: python


【解决方案1】:

如果您想找到最大的数字,为什么要不断地追加到highest_scorelowest_score?你不想只附加最大值或最小值吗?为什么不先计算呢?

nums = [6, 8, 9, 5, 3, 3, 5, 3]
highest_score = []
lowest_score = []

def calculate_Scores(nums):
  i = 1
  max = min = nums[0]
  # first, calculate the max and min.
  while i < len(nums):  # (possible improvement: replace this with a for loop)
    if nums[i] > max:
      max = nums[i]    # replace max with the new max
    if nums[i] < min:
      min = nums[i]    # replace min with the new min
    i += 1
  # now that you've done that, add them to the highest_score and lowest_score
  highest_score.append(max)
  lowest_score.append(min)

请注意,虽然这可能是一个有用的教育练习,但没有实际理由不只在这种情况下使用内置函数 max()min()以某种方式胜过其他元素的一个元素)。

【讨论】:

  • 非常感谢您的帮助!看来我没有正确理解方向。
猜你喜欢
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
相关资源
最近更新 更多