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

新手上路,请多包涵

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

 def high_and_low(numbers):

    return max(numbers), min(numbers)

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

但我有这个结果:

 ('8', ' ')

为什么我有 ' ' 作为最低数字?

原文由 ladybug 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 476
2 个回答

为了获得您想要的结果,您可以在传入的字符串上调用 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)

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

原文由 eric 发布,翻译遵循 CC BY-SA 3.0 许可协议

您正在将字符串传递给函数。为了达到预期的结果,您需要拆分字符串,然后将每个元素类型转换为 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)

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

原文由 Moinuddin Quadri 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题