从数字串中找出最高和最低的数字

2024-04-19 05:25:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个函数,返回列表中的最高和最低数字。

def high_and_low(numbers):

    return max(numbers), min(numbers)

print(high_and_low("1 2 8 4 5"))

但我有个结果:

('8', ' ')

为什么我把' '作为一个最低的数字?


Tags: and函数列表returndef数字minmax
3条回答

另一种(更快)使用映射的方法:

def high_and_low(numbers: str):
    #split function below will use space (' ') as separator
    numbers = list(map(int,numbers.split()))
    return max(numbers),min(numbers)

为了达到您想要的结果,您可以对传入的字符串调用split()。这基本上创建了输入字符串的list(),您可以在其上调用min()max()函数。

def high_and_low(numbers: str):
    """
    Given a string of characters, ignore and split on
    the space ' ' character and return the min(), max()

    :param numbers: input str of characters
    :return: the minimum and maximum *character* values as a tuple
    """
    return max(numbers.split(' ')), min(numbers.split(' '))

正如其他人指出的那样,您还可以传入一个要比较的值的列表,并可以直接在该列表上调用minmax函数。

def high_and_low_of_list(numbers: list):
    """
    Given a list of values, return the max() and 
    min()

    :param numbers: a list of values to be compared
    :return: the min() and max() *integer* values within the list as a tuple
    """
    return min(numbers), max(numbers)

原始函数在技术上是有效的,但是,它比较的是每个字符的数值,而不仅仅是整数的数值。

您正在将字符串传递给函数。为了获得所需的结果,需要分割字符串,然后将每个元素类型转换为int。那么只有minmax函数才能正常工作。例如:

def high_and_low(numbers):
    #    split numbers based on space     v
    numbers = [int(x) for x in numbers.split()]
    #           ^ type-cast each element to `int`
    return max(numbers), min(numbers)

样本运行:

>>> high_and_low("1 2 8 4 5")
(8, 1)

当前,您的代码正在根据字符的lexicographical order查找最小值和最大值。

相关问题 更多 >