从值列表中,我想创建一个新的值列表,直到它们累加一个值。
我是Python的新手,但我相信最好使用while循环来完成。
L = [1,2,3,4,5,6,7,8,9]
i = 0
s = 0
while i < len(L) and s + L[i] < 20:
s += L[i]
i += 1
答案 0 :(得分:7)
numpy
数组使这一过程变得简单
import numpy as np
arr = np.array(L)
arr[arr.cumsum() <= 20].tolist()
#[1, 2, 3, 4, 5]
答案 1 :(得分:5)
自从您标记了熊猫:
pd.Series(L, index=np.cumsum(L)).loc[:20].values
输出:
array([1, 2, 3, 4, 5], dtype=int64)
答案 2 :(得分:3)
您首先创建一个空列表,然后附加与您声明的条件相同的值。最后打印列表将返回与您的条件相匹配的已添加值:
L = [1,2,3,4,5,6,7,8,9]
i = 0
s = 0
new_list = []
while i < len(L) and s + L[i] < 20:
new_list.append(L[i])
s += L[i]
i += 1
print(new_list)
输出:
[1, 2, 3, 4, 5]
答案 3 :(得分:1)
如果我们在谈论pythonic,则for循环更有意义(也使用更好的变量名):
data = [1,2,3,4,5,6,7,8,9]
filtered = []
for num in data:
if num < 20:
filtered.append(num)
但是理解力也是Python且更短:
filtered = [num for num in data if num < 20]
然后使用sum
函数获取总和:
total = sum(filtered)
或者如果您只需要总和:
total = sum(n for n in data if n < 20)
答案 4 :(得分:0)
您可以轻松编写自己的生成器函数:
L = [1,2,3,4,5,6,7,8,9]
def takeuntil(lst, max_value = 0):
"""Yields elements as long as the cummulative sum is smaller than max_value."""
total = 0
for item in lst:
total += item
if total <= max_value:
yield item
else:
raise StopIteration
raise StopIteration
new_lst = [item for item in takeuntil(L, 20)]
print(new_lst)
哪个产量
[1, 2, 3, 4, 5]
答案 5 :(得分:-1)
如果您要从头到尾进行总结,那么(imo)将会是更多的pythonic方式
s = 0
for element in L:
if s + element < 20:
s += element
else:
break