Python 从数字串中查找最高和最低数字
我试图编写一个函数,返回列表中的最高和最低数字Python 从数字串中查找最高和最低数字,python,python-3.x,Python,Python 3.x,我试图编写一个函数,返回列表中的最高和最低数字 def high_and_low(numbers): return max(numbers), min(numbers) print(high_and_low("1 2 8 4 5")) 但我有一个结果: ('8', ' ') 为什么我要将'作为最低的数字?您正在将字符串传递给函数。为了获得所需的结果,需要拆分字符串,然后将每个元素强制转换为int。然后,只有min和max功能才能正常工作。例如: def high_and_low(
def high_and_low(numbers):
return max(numbers), min(numbers)
print(high_and_low("1 2 8 4 5"))
但我有一个结果:
('8', ' ')
为什么我要将
'
作为最低的数字?您正在将字符串传递给函数。为了获得所需的结果,需要拆分字符串,然后将每个元素强制转换为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)
当前,您的代码正在根据字符数查找最小值和最大值。您可以按
''
拆分字符串并将其作为数组传递
def high_and_low(numbers):
# split string by space character
numbers = numbers.split(" ")
# convert string array to int, also making list from them
numbers = list(map(int, numbers))
return max(numbers), min(numbers)
print(high_and_low("1 2 10 4 5"))
为了获得所需的结果,可以对传入的字符串调用
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)
您的原始函数在技术上是可以工作的,但是,它正在比较每个字符的数值,而不仅仅是整数的数值。使用
numbers\u list=[int(x)表示数字中的x。split()]
并在min()
和max()中使用numbers\u list
。
split();通过使用列表理解,所有字符串都将转换为整数。使用映射的另一种(更快)方法:
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)
空格低于所有其他字符。也许可以改为尝试整数列表?您将数字作为字符串传递,这是文本,而不是数字您的参数是字符串,而不是仍然将其作为文本传递的数字列表,因此“110 2”
将输出2作为最高数字。您是对的。。。我们可以通过映射@thomaswellert来修复这个问题。这段代码在Python3上失败,并带有“ValueError:min()arg是一个空序列”。。。。谢谢@markdickinson我们不能使用split()
和其他任何东西。。。像10这样的数字是错误的。我忘记了列表中的值仍然是字符串,我编辑了我的答案。它将从数字中找到min
和max
,作为字符串,这将是字典形式的min/max。例如:“11”将被视为小于“2”。在性能方面,这里将字符串拆分两次。