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

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

最佳答案

问题是 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]]

关于python - 函数将每个项目作为列表而不是具有相同项目的单个列表返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44843151/

相关文章:

用于 Traceroute 的 Python 脚本和打印文件中的输出显示错误(OSError : [Errno 2] No such file or directory) in Linux Mint

python - 使用 matplotlib 在图像文件上绘制半透明轮廓图

python - 如何将Python中的内容抓取到Excel中

c# - 从 c# unity 管道到 python 进程

python - 初级 Python 3 语法

python - 有谁知道如何根据txt文件将网格返回到shell中?

python - 在不丢失数据的情况下更新字典

python - 使用虚拟环境时的证书验证

python - 我的 Python SQLite 代码是否容易受到 SQL 注入(inject)?

python - 将值范围映射到字符串