我们如何获得 returns 列表中 Python 的函数?

How do we get a function that returns a list in Python?

所以我是 Python 的新手,这是我的代码:

def sum_is_less_than(numeric_value, list_of_numbers):
    total = 0
    for number in list_of_numbers:
        total = total + number
        if total > numeric_value:
            break
        print(total)

numeric_value = 100
list_of_numbers = [2, 3, 45, 33, 20, 14, 5]

sum_is_less_than(numeric_value, list_of_numbers)

这段代码的作用是添加列表的值,只要它在给定的数值之下。我希望代码输出列表中总和小于给定数值的前N个元素。

例如:[1,2,3,4,5,6] 给定数值为 10

我希望代码输出 [1,2,3],因为加 4 会使总和大于或等于给定的数值。

因此,如果您想从函数中获取列表,您实际上需要 return 一些东西。在这里,output 从一个空列表开始,并附加来自原始列表 list_of_numbers 的值,直到总和高于传递的数值。

def sum_is_less_than(numeric_value, list_of_numbers):
        total = 0
        output = []
        for number in list_of_numbers:
            total = total + number
            output.append(number) 
            if total > numeric_value:
                return output
        return output

一个用例是:

value = 10
list_of_numbers = [3,4,5,6]
list_sum_smaller_then_value = sum_is_less_than(numeric_value, list_of_numbers)
def sum_is_less_than(numeric_value, list_of_numbers):
    total = 0
    for number in list_of_numbers:
        total += number
        if total < numeric_value:
            print(number)
        else:
            break

numeric_value = 10
list_of_numbers = [1,2,3,4,5,6]

sum_is_less_than(numeric_value, list_of_numbers)

我会这样做(简短、高效且pythonic)。第一个表达式是 generator,意味着它不会计算不必要的值。

def sum_is_less_then(numeric_value, list_of_numbers: list):
    res = (sum(list_of_numbers[:idx]) for idx, _ in enumerate(list_of_numbers))
    return [x for x in res if x < numeric_value]

print (sum_is_less_then(30, [1,2,4,5,6,7,8,3,3,6]))
# result: [0, 1, 3, 7, 12, 18, 25]