函数将每个项作为列表返回,而不是返回具有相同项的单个列表

2024-04-16 13:51:51 发布

您现在位置:Python中文网/ 问答频道 /正文

输入示例:[5、9、2、4、1、3]

预期输出:[9,2,1]

函数将每个项作为一个列表返回,而不是返回一个包含以下相同项的列表。你知道吗

[9条]

[2条]

[1]

def divide_digits(a):
    """
    This is where the function's Document string (docstring) goes.
    """
    # make a shallow copy of the int_list and assign it to variable lst_copy
    lst_copy = a[:]
    # sort lst.copy
    lst_copy.sort()
    # as long as the lst_copy is not empty:
    while lst_copy:
        # get/pop the element from the beginning and at the end of the new_list
        largest_num = lst_copy.pop()
        smallest_num = lst_copy.pop(0)

        new_list = []
        # perform the division of two these elements
        result = largest_num / smallest_num
        # round down the result to the nearest integer
        # append the result of the division operation to the new list
        new_list.append(round(result))

        # return the new_list
        return new_list

Tags: andoftheto列表newisas
2条回答

使用^{}可以使用以下简明解决方案获得相同的结果:

my_list = [5, 9, 2, 4, 1, 3]
sorted_list = sorted(my_list)  # sorted doesn't sort in place, it returns a new sorted list
new_list = [round(sorted_list[-(i+1)] / sorted_list[i]) for i in range(len(sorted_list) // 2)]

输出:

>>> new_list
[9, 2, 1]

你的压痕不对。返回语句在while循环中。它应该在它之外,这意味着您也需要在循环之外定义新的\u列表。请尝试以下操作:

def divide_digits(a):
    """
    This is where the function's Document string (docstring) goes.
    """
    # make a shallow copy of the int_list and assign it to variable lst_copy
    lst_copy = a[:]
    # sort lst.copy
    lst_copy.sort()
    new_list = []
    # as long as the lst_copy is not empty:
    while lst_copy:
        # get/pop the element from the beginning and at the end of the new_list
        largest_num = lst_copy.pop()
        smallest_num = lst_copy.pop(0)

        # perform the division of two these elements
        result = largest_num / smallest_num
        # round down the result to the nearest integer
        # append the result of the division operation to the new list
        new_list.append(round(result))

        # return the new_list
    return new_list

相关问题 更多 >