示例输入:[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/