所以我是 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 會使總和大于或等于給定的數值。
uj5u.com熱心網友回復:
所以,如果你想從你的函式中得到一個串列,你需要實際回傳一些東西。在這里,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)
uj5u.com熱心網友回復:
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)
uj5u.com熱心網友回復:
我會這樣做(簡短,高效和pythonic)。第一個運算式是生成器,這意味著它不會不必要地計算值。
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474884.html
上一篇:如何將多個輸出變數放入串列中?
下一篇:此函式是否自動取消參考向量?
