在python中找到最小值和最大值 [英] Finding the minimum and maximum in python

查看:53
本文介绍了在python中找到最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须让用户输入一些数字,然后打印大小、总和、平均值、最小值和最大值.我可以得到前 3 件事,但我被困在最低和最高的一件事上.我遇到的问题是我不能使用 sort() 因为我需要将列表设为整数,但是你不能为 split()

I have to ask the user to put some numbers and then print the size, sum, average, minimum and maximum. I can get the first 3 things but I'm stuck on the minimum and maximum one. The problem I have is I can't use sort() because I need to make the list an integer one, but you can't use an integer list for split()

这是我的代码:

    number = raw_input('Enter number:')
    list_of_numbers = number.split()
    tally = 0
    sum = 0
      while number!= '':
        tally = tally + 1
        sum = sum + int(number)
        average = float(sum) / float(tally)
      number = raw_input('Enter number:')
    print "Size:", tally
    print "Sum:", sum
    print "Average:", average

有什么提示吗?谢谢

推荐答案

是否允许使用 Python 的内置函数?如果是,那就更容易了:

Are you allowed to use built-in functions of Python? If yes, it is easier:

number = raw_input('Enter number:')
list_of_numbers = number.split()

numbersInt = map(int, list_of_numbers) # convert string list to integer list

print("Size:",    len(numbersInt))
print("Min:",     min(numbersInt))
print("Max:",     max(numbersInt))
print("Sum:",     sum(numbersInt))
print("Average:", float(sum(numbersInt))/len(numbersInt) if len(numbersInt) > 0 else float('nan'))
# float conversion is only required by Python 2. 

where numbersInt = map(int, list_of_numbers) 将列表的每个字符串数字转换为整数.每个函数的含义如下:

where numbersInt = map(int, list_of_numbers) converts each string number of the list to an integer. Each function has the following meaning:

  • len 计算列表的长度
  • min 计算最小值
  • max 计算最大值
  • sum 计算列表的总和

Python 标准库中没有平均函数.但是你可以使用 numpy.mean() 代替.使用 pip install numpyconda install numpy 安装它,然后:

There isn't a mean function in Python standard library. But you can use numpy.mean() instead. Install it with pip install numpy or conda install numpy, then:

import numpy as np
print("Average: ", np.mean(numbersInt))

这篇关于在python中找到最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆