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

时间:2017-06-30 09:29:57

标签: 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

3 个答案:

答案 0 :(得分:5)

问题是new_list = []。您将在每次迭代中重新初始化列表。你必须去缩进return

def divide_digits(a):
    lst_copy = a[:]
    lst_copy.sort()
    new_list = []  # <-- this has to go here
    while lst_copy:
        largest_num = lst_copy.pop()
        smallest_num = lst_copy.pop(0)
        result = largest_num / smallest_num
        new_list.append(round(result))  # <-- on every iteration you append to the new_list
    return new_list  # <-- when you are done looping, return the new_list

使用列表解析的代码的较短替代方法是:

def divide_digits(a):
    lst_copy = sorted(a)  #<-- `sorted()`, unlike `.sort()` creates a new list
    return [round(lst_copy.pop() / lst_copy.pop(0)) for _ in a[::2]]

答案 1 :(得分:1)

你的缩进是错误的。你的return语句在while循环中。它应该在它之外,这意味着你需要在循环之外定义new_list。请尝试以下方法:

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

答案 2 :(得分:0)

使用list comprehension

,您可以使用以下简洁解决方案获得相同的结果
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]