我正在尝试编写一个函数,返回列表中最高和最低的数字。
def high_and_low(numbers):
return max(numbers), min(numbers)
print(high_and_low("1 2 8 4 5"))但我有这样的结果:
('8', ' ')为什么我把' '作为最低的数字?
发布于 2018-01-01 21:25:07
为了达到您想要的结果,您可以对传入的字符串调用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(' '))正如其他人指出的那样,您还可以传入一个列表,其中包含您想要比较的值,并且可以在此上直接调用、min、和max函数。
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)您的原始函数在技术上是可行的,但是,它是比较每个字符的数值,而不仅仅是整数值。
发布于 2018-01-01 21:09:18
您正在将字符串传递给函数。为了达到预期的结果,您需要拆分字符串,然后将每个元素类型转换为int。然后,只有您的min和max函数才能预期地工作。例如:
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)目前,您的代码正在根据字符的辞典顺序找到最小值和最大值。
发布于 2019-02-13 10:00:01
另一种(更快)使用映射的方法:
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)https://stackoverflow.com/questions/48053227
复制相似问题