python字符串查找数字_python – 从数字字符串中查找最高和最低数字

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

def high_and_low(numbers):

return max(numbers), min(numbers)

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

但我有这个结果:

('8', ' ')

为什么我的数字最低?

最佳答案 为了获得你想要的结果,你可以在你传入的字符串上调用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(' '))

正如其他人指出的那样,你也可以传入一个你想要比较的值列表,并可以直接调用最小和最大函数.

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)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值