遍历函数的列表



我有一个以列表为参数的函数(这里使用了一个非常简单的函数来关注我的问题)。

def some_lst_func(lst):
foo = len(lst)
return foo
lst1= [1, 6, 6, 7, 7, 5]
print(some_lst_func(lst1))

对于整个列表,这工作得很好,但我想增量传递列表([1],[1,6].....)到函数并记录每个输出(即增加列表的长度)。

下面是我尝试过的,但显然是不正确的,并且不确定我得到的输出是什么,我期望的是

1
2
3...
for num in lst1:
print(some_lst_func(lst1[:num]))

您需要遍历索引,而不是项:

def some_lst_func(lst):
return len(lst)
lst1= [1, 6, 6, 7, 7, 5]
for num in range(1, len(lst1) + 1):
print(some_lst_func(lst1[:num]))
# 1
# 2
# 3
# 4
# 5
# 6
# alternatively, using enumerate:
for num, _ in enumerate(lst1, start=1):
print(some_lst_func(lst1[:num]))

最新更新