python 使用循环查找列表中的最高分和最低分

0tdrvxhp  于 2023-05-27  发布在  Python
关注(0)|答案(2)|浏览(133)

更新:看来我理解代码的方向是错误的。
对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也去变量lowest_score?有没有其他办法让整个过程顺利进行?(不使用max()和min())

omqzjyyz

omqzjyyz1#

如果你试图找到最大的数字,为什么你不断地追加到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()

gcuhipw9

gcuhipw92#

There is a more easy way to do it 
If you want to user For Loop => 

nums = [6, 8, 9, 5, 3, 3, 5, 3]
highest_number = 0

for n in nums:
    if n > highest_score:
        highest_score = n
print(highest_number)

Or there is a built in function called max()which will do the same .

For ext print(max(nums)) => 9

相关问题