如何在python中找到字符串的最大值和最小值?

时间:2015-04-22 02:37:31

标签: python if-statement for-loop max min

这是我目前的计划。它正在输出不正确的最大值和最小值。我的if语句缺少什么?

def palin():
  max = 0
  min = 50
  numbers = "23","3","4","6","10"
  for x in numbers:

    if x>max:
      max=x
    if x<min:
      min=x

  print max
  print min

4 个答案:

答案 0 :(得分:9)

当您进行字符串比较或尝试使用带有字符串的min()max()时,您实际上是按字母顺序排序:

>>> sorted(numbers)
['10', '23', '3', '4', '6']

这就是为什么许多依赖于位置比较的built-in Python函数支持key参数:

>>> numbers
('23', '3', '4', '6', '10')
>>> sorted(numbers, key=int)
['3', '4', '6', '10', '23']
>>> min(numbers, key=int)
'3'
>>> max(numbers, key=int)
'23'

答案 1 :(得分:2)

你的号码是字符串。首先将它们转换为整数:

numbers = [int(num) for num in numbers]

def palin():
  max = 0
  min = 50
  numbers = "23","3","4","6","10"
  numbers = [int(num) for num in numbers]
  for x in numbers:

    if x>max:
      max=x
    if x<min:
      min=x

  print max
  print min

答案 2 :(得分:1)

python中的许多常见操作都有相关的built-in函数或相关的模块/包。

在这种情况下,max()min()是您的朋友。

str_numbers = ("23", "3", "4", "6", "10")
numbers = [int(n) for n in str_numbers ]  # convert to integers
max_value = max(numbers)
min_value = min(numbers)

max()min()也支持使用生成器表达式,因此您可以在函数本身中进行转换:

str_numbers = ("23", "3", "4", "6", "10")
max_value = max(int(n) for n in str_numbers)
min_value = min(int(n) for n in str_numbers)

答案 3 :(得分:1)

如果你已经安装了Numpy,你可以轻松获得结果。

import numpy as np

numbers = ["23","3","4","6","10"]
numbers = [int(n) for n in numbers]
numpy_array = np.array(numbers)
print 'Max:  ', numpy_array.max()
print 'Min:  ', numpy_array.min()
print 'Mean: ', numpy_array.mean()