簡體   English   中英

從數字字符串中查找最高和最低數字

[英]Find highest and lowest number from the string of numbers

我正在嘗試編寫一個返回列表中最高和最低編號的函數。

def high_and_low(numbers):

    return max(numbers), min(numbers)

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

但我有這個結果:

('8', ' ')

為什么我有' '作為一個最低的數字?

您正在將字符串傳遞給函數。 為了獲得所需的結果,您需要拆分字符串,然后將每個元素類型轉換為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)

目前,您的代碼是根據字符的詞典順序查找最小值和最大值。

為了獲得你想要的結果,你可以在你傳入的字符串上調用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)

您的原始函數在技術上是有效的,但是,它比較每個字符的數值而不僅僅是數值。

使用映射的另一種(更快)方式:

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)

您可以將字符串拆分為' '並將其作為數組傳遞

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"))

numbers_list=[int(x) for x in numbers.split()]使用numbers_list=[int(x) for x in numbers.split()]並在min()max()使用numbers_list split()'1 23 4 5'變為['1','23','4','5'] ; 通過使用列表推導,所有字符串都轉換為整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM